从python中的字典列表中获取值列表 [英] Get a list of values from a list of dictionaries in python

查看:2558
本文介绍了从python中的字典列表中获取值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表,我需要从字典中的给定键中获取值列表(所有字典都有相同的键)。

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.

推荐答案

使用简单的列表理解(如果你确定每个字典都有e键):

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]

否则,您需要先检查:

In [11]: [d['key'] for d in l if 'key' in d]
Out[11]: [1, 2, 3]

这篇关于从python中的字典列表中获取值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆