从词典列表中只打印一项的快捷方式

2024-06-13 14:42:04 发布

您现在位置:Python中文网/ 问答频道 /正文

l = [
    {'bob':'hello','jim':'thanks'},
    {'bob':'world','jim':'for'},
    {'bob':'hey','jim':'the'},
    {'bob':'mundo','jim':'help'}
]

for dict in l:
    print dict['jim']

有没有一条线或Python式的方法来做这件事? 我试图检索字典列表中只有一项的列表


Tags: the方法inhello列表forworldhelp
3条回答

当然,例如:

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

是的,功能编程良好:

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

并且不要使用dict作为变量名。它屏蔽了dict()内置的。在

相关问题 更多 >