从字典列表中获取值列表? [英] Get a list of values from a list of dictionaries?
本文介绍了从字典列表中获取值列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典列表,我需要从字典中的给定键中获取值的列表(所有字典都具有相同的键).
I have a list of dictionaries, and I need to get a list of the values from a given key from the dictionary (all the dictionaries have those same key).
例如,我有:
l = [ { "key": 1, "Val1": 'val1 from element 1', "Val2": 'val2 from element 1' },
{ "key": 2, "Val1": 'val1 from element 2', "Val2": 'val2 from element 2' },
{ "key": 3, "Val1": 'val1 from element 3', "Val2": 'val2 from element 3' } ]
我需要得到1、2、3.
I need to get 1, 2, 3.
我当然可以用:
v=[]
for i in l:
v.append(i['key'])
但是我想找到一种更好的方法.
But I would like to get a nicer way to do so.
推荐答案
Using a simple list comprehension (if you're sure every dictionary has the key):
In [10]: [d['key'] for d in l]
Out[10]: [1, 2, 3]
否则,您需要首先检查是否存在:
Otherwise you'll need to check for existence first:
In [11]: [d['key'] for d in l if 'key' in d]
Out[11]: [1, 2, 3]
这篇关于从字典列表中获取值列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文