python help with extracting value from list
lst = [{"id": 1, "name": "ernest"}, .... {"id开发者_如何学编程": 16, name:"gellner"}]
for d in lst:
if "id" in d and d["id"] == 16:
return d
I want to extract the dictionary that the key "id" equals to "16" from the list.
Is there a more pythonic way of this?
Thanks in advance
Riffing on existing answers to get out of the comments:
Consider using a generator expression when you only need the first matching element out of a sequence:
d16 = (d for d in lst if d.get('id') == 16).next()
This is a pattern you'll see in my code often. This will raise a StopIteration
if it turns out there weren't any items in lst
that matched the condition. When that's expected to happen, you can either catch the exception:
try:
d16 = (d for d in lst if d.get('id') == 16).next()
except StopIteration:
d16 = None
Or better yet, just unroll the whole thing into a for-loop that stops
for d16 in lst:
if d16.get('id') == 16:
break
else:
d16 = None
(the else:
clause only gets run if the for loop exhausts its input, but gets skipped if the for loop ends because break
was used)
This does it. Whether or not it's "cleaner" is a personal call.
d16 = [d for d in lst if d.get('id', 0) == 16][0]
This initial approach fails if there is no dictionary with id 0. You can overcome that somewhat like this:
d16 = [d for d in lst if d.get('id', 0) == 16]
if d16: d16 = d16[0]
This will prevent the index error, but d16 will be an empty list if there is no dictionary in the container that matches the criteria.
One slight improvement if not found:
d16 = ([d for d in lst if d.get('id', 0) == 16] + [None])[0]
精彩评论