Shortcut to print only 1 item from list of dictionaries
l = [
{'bob':'hello','jim':'thanks'},
{'bob':'world','jim':'for'},
{'bob':'hey','jim':'the'},
{'bob':'mundo','jim':'help'}
]
for dict in l:
p开发者_运维百科rint dict['jim']
Is there a one liner or pythonic way of doing this? I'm trying to retrieve a list of just 1 item in a list of dictionaries
[d['jim'] for d in l]
And don't use dict
as a variable name. It masks the dict()
built-in.
Yes, with good ol' functional programming:
map(lambda d: d['jim'], l)
Sure, for example:
In []: l
Out[]:
[{'bob': 'hello', 'jim': 'thanks'},
{'bob': 'world', 'jim': 'for'},
{'bob': 'hey', 'jim': 'the'},
{'bob': 'mundo', 'jim': 'help'},
{'bob': 'gratzie', 'jimmy': 'a lot'}]
In []: [d['jim'] for d in l if 'jim' in d]
Out[]: ['thanks', 'for', 'the', 'help']
精彩评论