如何从字典列表中提取特定键的所有值? [英] How do I extract all the values of a specific key from a list of dictionaries?
问题描述
我有一个列表,列表中都有相同的结构。例如:
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 value
items from each dictionary in the list:
['one', 'two', 'three']
我可以遍历列表并使用for循环来提取每个值:
I can of course iterate through the list and extract each value using a for loop:
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.
推荐答案
如果您只需要迭代一次值,请使用生成器表达式:
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)
<另一个(深奥)选项可能是使用 map
与 itemgetter
- 它可能比生成器表达式稍快,否则,取决于具体情况:
Another (esoteric) option might be to use map
with itemgetter
- it could be slightly faster than the generator expression, or not, depending on circumstances:
from operator import itemgetter
generator = map(itemgetter('value'), test_data)
如果你绝对需要一个列表,列表的理解速度比迭代 list.append
,因此:
And if you absolutely need a list, a list comprehension is faster than iterated list.append
, thus:
results = [ item['value'] for item in test_data ]
这篇关于如何从字典列表中提取特定键的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!