[Tutor] sqlite question

Peter Otten __peter__ at web.de
Tue Jun 11 12:38:56 CEST 2013


Khalid Al-Ghamdi wrote:

> Hi,
> 
> I have a dictionary with keys as employee badges and values as their
> names. Both key and value are strings.
> 
> I want to read the badges from a sql select and use that to look up the
> names in the dictionary. But since the result is a tuple, it doesnt' work.
> 
> how can i overcome this?
> 
> 
>    1. >>> for data in cur.execute('select badge from sched'):
>    2.         r_data()[data]
>    3.
>    4.
>    5. Traceback (most recent call last):
>    6.   File "<pyshell#19>", line 2, in <module>
>    7.     r_data()[data]
>    8. KeyError: (80385,)

(80385,) instead of just 80385 should give you a hint that data is a tuple 
with a single item. Once you unpack it with key = data[0] you should be 
alright. So:

for data in cur.execute(...):
    badge = data[0]
    r_data()[badge]

You can make the unpacking implicit to the for loop with

for badge, in cur.execute(...): # note the trailing comma
    r_data()[badge]

or somewhat less subtle

for [badge] in cur.execute(...):
    r_data()[badge]

>    PS: the r_data () above is just a func that returns the before
>    mentioned dictionary. Here is r_data().
> 
>    1. def r_data():
>       2.     d={}
>       3.     with open('data.csv') as f:
>       4.         reader = csv.reader(f)
>       5.         for sn, badge, name, grp, major, track, stage, tc,
>       subject,
>        course in reader:
>       6.             d[badge]=name
>       7.     return d

I assume in your final code you are not going to reread the csv for every 
row in the sched table...



More information about the Tutor mailing list