[英]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.您不应该使用list
或str
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.