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

问题描述

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...