我有一个字典列表,我需要从字典中获取给定键的值列表(所有字典都有相同的键)。
例如,我有:
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。
当然,我可以得到它:
v=[]
for i in l:
v.append(i['key'])
但我希望能有更好的方法。
答案 0 :(得分:11)
使用简单的list comprehension(如果您确定每个字典都有密钥):
In [10]: [d['key'] for d in l]
Out[10]: [1, 2, 3]
否则你首先需要检查是否存在:
In [11]: [d['key'] for d in l if 'key' in d]
Out[11]: [1, 2, 3]