从词典列表中获取新列表

Ano*_*ity 1 python dictionary list

从字典对象列表开始,如何根据键获取包含一些字典值的新列表?

例如:

my_list = [ {'foo':1},{'bar':2},{'foo':3} ]
new_list = grab_values(my_list, 'foo')
Run Code Online (Sandbox Code Playgroud)

我们想要什么:

new_list = [1, 3]
Run Code Online (Sandbox Code Playgroud)

Lev*_*sky 8

首先想到的是:

In [2]: [x['foo'] for x in my_list if 'foo' in x]
Out[2]: [1, 3]
Run Code Online (Sandbox Code Playgroud)

作为一个功能:

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]
Run Code Online (Sandbox Code Playgroud)