简体   繁体   中英

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:
    print 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM