简体   繁体   English

获取字典列表的所有值

[英]Get all values of list of dictionaries

I have list of dictionaries like this:我有这样的字典列表:

count = [{'A': 0}, {'B': 2}, {'C': 4}]

I want convert count to something like this:我想将count转换为这样的东西:

count = [0, 2, 4]

You can do that with list comprehension:您可以通过列表理解来做到这一点:

count = [{'A': 0}, {'B': 2}, {'C': 4}]
[j for i in count for j in i.values()]

Output: Output:

[0, 2, 4]

You can extract the values from each dictionary using a comprehension, and then you can use itertools.chain() to extract the values from each dictionary into one long iterator.您可以使用理解从每个字典中提取值,然后可以使用itertools.chain()将每个字典中的值提取到一个长迭代器中。 This gives us a chain object, which we need to turn into a list using list() .这给了我们一条chain object,我们需要使用list()将它变成一个列表。

from itertools import chain

list(chain.from_iterable(item.values() for item in count))

This outputs:这输出:

[0, 2, 4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM