473,666 Members | 2,080 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simple db using list comprehensions

Hi all

From time to time there is a request for a simple way of storing and
accessing data without using a full SQL database.

I had this requirement recently, and I was pleasantly surprised by how
much I could achieve with a simple Python list and list
comprehensions.

Assume the need to store data consisting of first name, surname and
phone number. To ensure uniqueness, I use an additional column to
store a unique id, which can just be a 'next number'.

To create the table -
table = []

To initialise it with a couple of rows -
table.append([1,'Frank','Mill man',12345])
table.append([2,'John','Smith ',54321])

To get the last id used -
last_id = max([row[0] for row in table])

Alternatively, if you know the rows are in id sequence -
last_id = table[-1][0]

To add a new row -
firstname = 'Fred'
surname = 'Jones'
phone = 23456

First, ensure first name and surname are unique -
rows = [row for row in table if row[1] == firstname and row[2] ==
surname]
if len(rows):
errmsg = 'Already exists'

If ok, add the row -
last_id += 1
table.append([last_id,firstna me,surname,phon e])

To select all rows according to some criteria (eg surnames starting
with 'M') -
rows = [row for row in table if row[2][0] == 'M']

If you need a copy of the rows -
rows = [row[:] for row in table if row[2][0] == 'M']

To sort the rows in surname sequence -
rows = [[row[2],row] for row in rows] # prepend surname to row for
sorting
rows.sort()
rows = [row[1] for row in rows] # remove prepended surname

To select and sort at the same time -
rows = [[row[2],row] for row in table if row[2][0] == 'M']
rows.sort()
rows = [row[1] for row in rows]

To amend a phone number if you know the first name and surname -
rows = [row for row in table if row[1] == 'Fred' and row[2] ==
'Jones']
if not rows:
errmsg = 'not found'
elif len(rows) > 1:
errmsg = 'more than one row found'
else:
rows[0][3] = phone

To delete a row if you know the first name and surname -
rows = [row for row in table if row[1] == 'Fred' and row[2] ==
'Jones']
if not rows:
errmsg = 'not found'
elif len(rows) > 1:
errmsg = 'more than one row found'
else:
pos = [row[0] for row in table].index(rows[0][0])
del table[pos]

To delete all rows with a phone number of 0 -
ids = [row[0] for row in table]
rows = [row[0] for row in table if row[3] == 0]
for row in rows:
pos = ids.index(row)
del table[pos]
del ids[pos]

I have not tested all of these, but you get the idea.

I did not have to save the data, but if you need to, I am sure you can
pickle it.

Hope this is of interest.

Frank Millman
Jul 18 '05 #1
0 1519

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1631
by: Elaine Jackson | last post by:
List comprehensions don't work the way you intuitively expect them to work. I realize many people have no intuitions about how list comprehensions 'should' work, so if you recognize yourself in this description, feel free to go back to whatever you were doing before. If you're still here, though, I invite you to consider the following definition: partitions = lambda n: ]++x for x in partitions(n-k) for k in range(1,n)] As defined...
24
3342
by: Mahesh Padmanabhan | last post by:
Hi, When list comprehension was added to the language, I had a lot of trouble understanding it but now that I am familiar with it, I am not sure how I programmed in Python without it. Now I see that generator expressions have been added to the language with 2.4 and I question the need for it. I know that it allows for lazy evaluation which speeds things up for larger lists but why was it necessary to add it instead of improving list...
23
2254
by: Mike Meyer | last post by:
Ok, we've added list comprehensions to the language, and seen that they were good. We've added generator expressions to the language, and seen that they were good as well. I'm left a bit confused, though - when would I use a list comp instead of a generator expression if I'm going to require 2.4 anyway? Thanks, <mike --
24
3929
by: Mandus | last post by:
Hi there, inspired by a recent thread where the end of reduce/map/lambda in Python was discussed, I looked over some of my maps, and tried to convert them to list-comprehensions. This one I am not sure how to conver: Given three tuples of length n, b,i and d, I now do:
30
3462
by: Steven Bethard | last post by:
George Sakkis wrote: > "Steven Bethard" <steven.bethard@gmail.com> wrote: >> Dict comprehensions were recently rejected: >> http://www.python.org/peps/pep-0274.html >> The reason, of course, is that dict comprehensions don't gain you >> much at all over the dict() constructor plus a generator expression, >> e.g.: >> dict((i, chr(65+i)) for i in range(4)) > > Sure, but the same holds for list comprehensions: list(i*i for i in
7
1609
by: Steven Bethard | last post by:
Tom Anderson <twic@urchin.earth.li> wrote: > Sounds good. More generally, i'd be more than happy to get rid of list > comprehensions, letting people use list(genexp) instead. That would > obviously be a Py3k thing, though. Alex Martelli wrote: > I fully agree, but the BDFL has already (tentatively, I hope) > Pronounced that the form will stay in Py3K as syntax sugar for > list(...). I find that to be a truly hateful prospect, but...
6
2161
by: Heiko Wundram | last post by:
Hi all! The following PEP tries to make the case for a slight unification of for statement and list comprehension syntax. Comments appreciated, including on the sample implementation. === PEP: xxx Title: Unification of for-statement and list-comprehension syntax
6
1394
by: Lonnie Princehouse | last post by:
List comprehensions appear to store their temporary result in a variable named "_" (or presumably "_", "_" etc for nested comprehensions) In other words, there are variables being put into the namespace with illegal names (names can't contain brackets). Can't someone come up with a better hack than this? How about using "_1", "_2", etc, or actually making "_" a list of lists and using the real first, second, third elements? This is...
4
3052
by: beginner | last post by:
Hi All, If I have a list comprehension: ab= c = "ABC" print c
0
8445
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8640
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5664
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4369
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2771
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1776
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.