Python 如何从字典列表中提取特定键的所有值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25148611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I extract all the values of a specific key from a list of dictionaries?
提问by James Mertz
I have a list of dictionaries that all have the same structure within the list. For example:
我有一个字典列表,它们在列表中都具有相同的结构。例如:
test_data = [{'id':1, 'value':'one'}, {'id':2, 'value':'two'}, {'id':3, 'value':'three'}]
I want to get each of the valueitems from each dictionary in the list:
我想value从列表中的每个字典中获取每个项目:
['one', 'two', 'three']
I can of course iterate through the list and extract each value using a for loop:
我当然可以遍历列表并使用 for 循环提取每个值:
results = []
for item in test_data:
results.append(item['value'])
however my data set is quite large. I'm wondering if there's a faster way to this.
但是我的数据集非常大。我想知道是否有更快的方法。
采纳答案by Antti Haapala
If you just need to iterate over the values once, use the generator expression:
如果您只需要迭代一次值,请使用生成器表达式:
generator = ( item['value'] for item in test_data )
...
for i in generator:
do_something(i)
Another (esoteric) option might be to use mapwith itemgetter- it could be slightly faster than the generator expression, or not, depending on circumstances:
另一个(深奥的)选项可能是使用mapwith itemgetter- 它可能比生成器表达式稍快,也可能不快,具体取决于情况:
from operator import itemgetter
generator = map(itemgetter('value'), test_data)
And if you absolutely need a list, a list comprehension is faster than iterated list.append, thus:
如果你绝对需要一个列表,列表理解比 iterated 更快list.append,因此:
results = [ item['value'] for item in test_data ]
回答by levi
You can do this:
你可以这样做:
result = map (lambda x:x['value'],test_data)
回答by agconti
If your data is truly large, a generatorwill be more efficient:
如果您的数据确实很大,生成器会更高效:
list((object['value'] for object in test_data))
ex:
前任:
>>> list((object['value'] for object in test_data))
['one', 'two', 'three']
The generator portion is this:
生成器部分是这样的:
(object['value'] for object in test_data)
By wrapping that in a list(), you exhaust the generator and return its values nicely in an array.
通过将其包装在 a 中list(),您可以耗尽生成器并在数组中很好地返回其值。

