我正在尝试从字典词典中获取名单列表......
list = {'1':{'name':'fred'}, '2':{'name':'john'}}
# this code works a-ok
for key, value in list.items():
names = []
for key, value in list.items():
names.append(value['name'])
# and these consecutive comprehensions also work...
keys = [value for key, value in list.items()]
names = [each['name'] for each in keys]
但最后两个如何组合?
答案 0 :(得分:9)
>>> d = {'1':{'name':'fred'}, '2':{'name':'john'}}
您可以对列表理解使用以下修改
>>> [value.get('name') for key, value in d.items()]
['john', 'fred']
虽然在这种情况下,你不需要key
来做任何事情,所以你可以做到
>>> [value.get('name') for value in d.values()]
['john', 'fred']
答案 1 :(得分:6)
names = [value['name'] for value in list.values()]
答案 2 :(得分:2)
names = [value['name'] for key, value in list.items()]
由于value
部分是在for
部分中定义的,因此您可以对value
执行对理解项目部分的操作。如上所述,您可以使用list.values()
来简化此操作。
答案 3 :(得分:1)
names = [value['name'] for key, value in list.items()]