我有一个字典列表,像这样:
[{'value': 'apple', 'blah': 2},
{'value': 'banana', 'blah': 3} ,
{'value': 'cars', 'blah': 4}]
我想要['苹果','香蕉','汽车']
做这件事最好的方法是什么?
我有一个字典列表,像这样:
[{'value': 'apple', 'blah': 2},
{'value': 'banana', 'blah': 3} ,
{'value': 'cars', 'blah': 4}]
我想要['苹果','香蕉','汽车']
做这件事最好的方法是什么?
当前回答
遵循这个例子——
songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]
print("===========================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')
playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')
# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))
其他回答
对于这样一个非常简单的例子,理解伊斯梅尔·巴达维的答案绝对是正确的。
但是,当事情变得更加复杂,并且需要开始编写包含复杂表达式的多子句或嵌套推导时,就值得考虑其他替代方案了。有几种不同的(准)标准方法可以在嵌套的字典和列表结构上指定xpath样式的搜索,例如JSONPath、DPath和KVC。在PyPI上有很好的库供他们使用。
下面是一个名为dpath的库的示例,展示了它如何简化一些更复杂的东西:
>>> dd = {
... 'fruits': [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3}],
... 'vehicles': [{'value': 'cars', 'blah':4}]}
>>> {key: [{'value': d['value']} for d in value] for key, value in dd.items()}
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
'vehicles': [{'value': 'cars'}]}
>>> dpath.util.search(dd, '*/*/value')
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
'vehicles': [{'value': 'cars'}]}
或者,使用jsonpath-ng:
>>> [d['value'] for key, value in dd.items() for d in value]
['apple', 'banana', 'cars']
>>> [m.value for m in jsonpath_ng.parse('*.[*].value').find(dd)]
['apple', 'banana', 'cars']
乍一看,这一点可能不那么简单,因为find返回匹配对象,其中除了匹配值之外还包括各种内容,比如直接指向每个项的路径。但是对于更复杂的表达式,能够指定像'*.[*]这样的路径。Value '而不是每个*的理解子句会产生很大的不同。此外,JSONPath是一种语言不可知的规范,甚至有在线测试人员可以非常方便地进行调试。
假设每个字典都有一个值键,你可以这样写(假设你的列表名为l)
[d['value'] for d in l]
如果价值可能丢失,您可以使用
[d['value'] for d in l if 'value' in d]
一个非常简单的方法是:
list1=['']
j=0
for i in com_list:
if j==0:
list1[0]=(i['value'])
else:
list1.append(i['value'])
j+=1
输出:
['apple', 'banana', 'cars']
[x['value'] for x in list_of_dicts]
遵循这个例子——
songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]
print("===========================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')
playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')
# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))