繁体   English   中英

仅打印字典列表中的一项的快捷方式

[英]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']

有没有一种衬里或pythonic的方式来做到这一点? 我正在尝试检索字典列表中只有一项的列表

[d['jim'] for d in l]

并且不要使用dict作为变量名。 它掩盖了dict()内置。

是的,具有良好的函数式编程:

map(lambda d: d['jim'], l)

当然可以,例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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