[Tutor] Tuple and Dicts?

Kent Johnson kent37 at tds.net
Thu Nov 9 19:41:05 CET 2006


Basil Shubin wrote:
> Hi friends!
> 
> Imagine the tuple that has dictionaries as it's item:
> 
>>>> print data
> ({'id': 0, 'title': 'Linux'}, {'id': 1, 'title': 'FreeBSD'})
> 
> How I can get index of tuple item where dict's key 'id' equal to
> appropriate value? And can this be done without 'for' loops, just in one
> string?

If you must...this will break if there is no match, and it will always 
enumerate the entire data list:
[ i for i, d in enumerate(data) if d['id']== id_to_match ][0]

For the readable version, which won't break if the id is missing, and 
may be faster depending on the data:

for i, d in enumerate(data):
   if d['id'] == id_to_match:
     break
else:
   i = None # or whatever you want to do to signal no match


Alternately, maybe you should be storing data in a dict indexed by id 
instead of in a list?

Kent



More information about the Tutor mailing list