问题描述
|
l = [
{\'bob\':\'hello\',\'jim\':\'thanks\'},{\'bob\':\'world\',\'jim\':\'for\'},{\'bob\':\'hey\',\'jim\':\'the\'},{\'bob\':\'mundo\',\'jim\':\'help\'}
]
for dict in l:
print dict[\'jim\']
有没有一种衬里或蟒蛇的方式来做到这一点?
我正在尝试检索词典列表中仅一项的列表
解决方法
[d[\'jim\'] for d in l]
并且不要将ѭ2用作变量名。它掩盖了内置的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\']