Odd-R. Hogstad wrote (in private e-mail, with scarcely private contents):
In comp.lang.python, you 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?

      
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, however I was hoping for something even simpler,
as I am to use it in a <tal:block tal:define="d python:
  
Sorry, I don't know what <tal:block etc etc means.

And I don't know what "even simpler" could mean. Once you have the list and have defined the function, you can simply deploy it wherever you need the value.
current_oid = whatever
...
current_dict = oidfinder(current_oid, the_list)
Is this the only way to do it? What if I know that the oid
I am looking for is pressent?


  
Answering the 2nd question first: ignore the possiblility that the oidfinder() will return None i.e. just chill out.

Other ways:
(a) use a list comprehension inline:

current_dict = [d for d in the_list if d['oid'] == current_oid][0]
# this is a tad ugly and will blow up if the sought oid is not present -- but that can't happen, can it ? :-)

(b) preprocess the weird/baroque/byzantine list that you have got.

the_dict = {}
for d in the_list:
    the_dict[d['oid']] = d

then you do this:

current_dict = the_dict[current_oid]
# Simpler than that it cannot be.

Now a couple of questions for you:

(1) Have you contemplated that an oid can appear more than once in the list?
(2) What in tarnation is an "oid"?????

Cheers,
John
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to