find a specified dictionary in a list
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Sat Jul 23 09:33:36 EDT 2005
On Fri, 22 Jul 2005 12:42:04 +0000, Odd-R. wrote:
> On 2005-07-22, John Machin <sjmachin at lexicon.net> wrote:
>> Odd-R. wrote:
>>> I have this list:
>>>
>>> [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]
>>>
>>> All the dictionaries of this list are of the same form, and all the oids
>>> are distinct. If I have an oid and the list, how is the simplest way of
>>> getting the dictionary that holds this oid?
Instead of keeping a list of dictionaries, keep a dict of dicts, indexed
by the oid:
D = {1: {'i': 'milk'}, 2: {'i': 'butter'}, 3: {'i': 'cake'}}
Then you can extract a dictionary with a single call:
thedict = D[oid]
or just grab the item you want directly:
food = D[oid]['i']
No mess, no fuss. Ninety percent of the work is choosing your data
structures correctly.
>> Something like this:
>>
>> def oidfinder(an_oid, the_list):
>> for d in the_list:
>> if d['oid'] == an_oid:
>> return d
>> return None
>> # These are not the oids you are looking for.
>
> Thank you for your help, but I was hoping for an even simpler
> solution, as I am suppose to use it in a
> <tal:block tal:define="p python: sentence.
I don't understand what that means. Can you explain please?
--
Steven.
More information about the Python-list
mailing list