从字典对象列表开始,如何根据键获取仅包含一些字典值的新列表?
例如:
my_list = [ {'foo':1},{'bar':2},{'foo':3} ]
new_list = grab_values(my_list, 'foo')
我们想要什么:
new_list = [1, 3]
答案 0 :(得分:8)
首先想到的是:
In [2]: [x['foo'] for x in my_list if 'foo' in x]
Out[2]: [1, 3]
作为一项功能:
In [3]: def grab_values(l, key):
...: return [x[key] for x in l if key in x]
...:
In [4]: grab_values(my_list, 'foo')
Out[4]: [1, 3]