使用对象列表中的特定键生成列表

时间:2013-10-09 21:49:24

标签: python list dictionary

几年内没有使用过很多Python,并且很难记住如何做到这一点。

src = [
    {a: 1},
    {a: 2, b: 'foo'},
    {a: 3}
]

#python magic here outputs:
#[1,2,3]

*为了清晰起见而编辑

1 个答案:

答案 0 :(得分:3)

我不确定你想要哪两个:

def get_all_values(list_o_dicts):
    return [value for a_dict in list_o_dicts for value in a_dict.values()]

......或......

def get_values(list_o_dicts, key):
    return [a_dict[key] for a_dict in list_o_dicts]

这里有两个实际操作,使用一个例子,(a)实际上是有效的Python,(b)有其他值,所以区别有所不同:

>>> src = [
...     {'a': 1, 'b': 2},
...     {'a': 3}
... ]
>>> get_all_values(src)
[1, 2, 3]
>>> get_values(src, 'a')
[1, 3]
相关问题