简体   繁体   English

如何在保留所有元素的同时提取字典列表中的所有键? (Python)

[英]How can I extract all keys in a list of dictionaries while keeping all elements? (Python)

Suppose I have the following list of dictionaries:假设我有以下字典列表:

list1 = [{'1': 1}, {'1': 1}, {'0': 1}, {'1': 1}, {'1': 1}, {'0': 1}]

how can I extract all the keys into a single list?如何将所有键提取到一个列表中? The desired output should look like:所需的 output 应如下所示:

li = [1,1,0,1,1,0]

I tried to use我试着用

randlis = [list[i].keys() for i in range len(list1)]

This doesn't work since the output includes the type:这不起作用,因为 output 包括以下类型:

[dict_keys(['1']), dict_keys(['1']), dict_keys(['0'])]

Thanks!谢谢!

You can simply loop over the elements using list comprehension您可以使用list comprehension简单地遍历元素

[key for _dict in list for key in _dict.keys()]
#['1', '1', '0', '1', '1', '0']

Note.笔记。 You should not use list or str int etc for naming variables.您不应该使用liststr int等来命名变量。 I have kept it the same in the example so you understand the loop better.我在示例中保持不变,以便您更好地理解循环。 Please change your var name to something else.请将您的 var 名称更改为其他名称。

You can use chain from itertools:您可以使用来自 itertools 的链:

list1 = [{'1': 1}, {'1': 1}, {'0': 1}, {'1': 1}, {'1': 1}, {'0': 1}]

from itertools import chain

randlis = list(chain(*list1))

print(randlis)
['1', '1', '0', '1', '1', '0']

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

相关问题 从字典列表中提取所有键 - Extract all keys from a list of dictionaries 带有字典的列表-计算所有键的值(Python) - List with dictionaries - count values for all keys (Python) 如何在Python中使用字典列表中的所有字典 - How can make all dictionaries inside list of dictionaries Default in Python 如何在遍历字典列表时忽略所有字典的单个/多个键? - How to ignore a single/multiple keys of all the dictionaries while looping over a list of dictionaries? 将字典字典的所有键提取为列表或 np.array - extract all keys of a dictionary of dictionaries as a list or np.array 如何从字典列表中获取所有值的列表? - How can I get a list of all values from a list of dictionaries? 如何使用Python和ElementTree从XML文件的所有元素中提取所有内容? - How can I extract all content from all elements of an XML file with Python and ElementTree? 如何将 python LIST 中的项目与 DICTIONARY 键进行比较,然后使用 LIST 的所有元素构造字典 - How do i compare items in a python LIST to DICTIONARY keys and then construct a dictionary with all elements of the LIST 如何使用python中的字典合并其他列表中某个项目的所有值? - how can i combine all the values of an item in other list using dictionaries in python? 使用Python中的值更新字典列表中的所有匹配键 - Update all matching keys in list of dictionaries with value in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM