简体   繁体   English

从词典列表中获取值列表?

[英]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). 我有一个字典列表,我需要从字典中获取给定键的值列表(所有字典都有相同的键)。

For example, I have: 例如,我有:

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' } ]

I need to get 1, 2, 3. 我需要得到1分,2分,3分。

Of course, I can get it with: 当然,我可以得到它:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM