我有一个字典列表,我需要从字典的给定键中获取值的列表(所有字典都具有相同的键)。
例如,我有:
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'])
但是我想找到一种更好的方法。
使用简单的列表推导(如果您确定每个字典都有键):
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]