[Tutor] Query dictionaries with sql-like syntax

Kent Johnson kent37 at tds.net
Wed Jul 13 16:01:28 CEST 2005


Negroup - wrote:
> Anyway, I'm learning Python and just for exercise I'll try to
> implement a simple sql-like interface for querying dictionaries!

It might be a better use of your time to learn about Python's built-in abilities to manipulate lists and dictionaries, which are powerful and simple. You don't say what kind of queries you need to do but they may be very simple to express directly in Python. My guess is that simple loops and list comprehensions would do a lot of the work for you.

I'm going to guess that your data is expressed as lists of dictionaries. For example here is a list with two records:

 >>> r1 = { 'fname' : 'Kent', 'lname' : 'Johnson' }
 >>> r2 = { 'fname' : 'Negroup', 'lname' : None }
 >>> data = [ r1, r2 ]
 >>> data
[{'lname': 'Johnson', 'fname': 'Kent'}, {'lname': None, 'fname': 'Negroup'}]

Suppose I want to find everyone whose first name is 'Kent'. This is easy to do with a list comprehension:

 >>> [ r for r in data if r['fname'] == 'Kent' ]
[{'lname': 'Johnson', 'fname': 'Kent'}]

What if I want to compute a new field in the form lastname, firstname but handle the case of lastname == None? A helper function to compute the new field looks like this:

 >>> def makeLnameFname(fname, lname):
 ...   if not lname: return fname
 ...   return '%s, %s' % (lname, fname)
 ...

Let's try it out to make sure it works:

 >>> makeLnameFname('Kent', 'Johnson')
'Johnson, Kent'
 >>> makeLnameFname('Negroup', None)
'Negroup'

Now we go through the data adding a 'fullname' attribute to each record. A for loop makes short work of this:

 >>> for r in data:
 ...   r['fullname'] = makeLnameFname(r['fname'], r['lname'])
 ...
 >>> data
[{'lname': 'Johnson', 'fullname': 'Johnson, Kent', 'fname': 'Kent'}, {'lname': None, 'fullname': 'Negroup', 'fname': 'Negroup'}]

I hope you can see that this is vastly easier than implementing an SQL engine. Python is very powerful for manipulating data structures and learning how to use that power is well worth the time.

Kent



More information about the Tutor mailing list