[英]Python Dictionary: Create a list for all keys in dict, another for all values in dict
I have a dictionary which looks like this: Counter({'firstKey': 1708, 'secondKey': 1589, 'thirdKey': 1424})
我有一个看起来像这样的字典: Counter({'firstKey': 1708, 'secondKey': 1589, 'thirdKey': 1424})
I would like to have two lists:我想要两个列表:
First list should list all keys: ['firstKey', 'secondKey', 'thirdKey']
第一个列表应该列出所有键: ['firstKey', 'secondKey', 'thirdKey']
Second list should list all values: [1708, 1589, 1424]
第二个列表应列出所有值: [1708, 1589, 1424]
Please help请帮忙
Usingdict.keys()
and dict.values()
and casting them to list
:使用dict.keys()
和dict.values()
并将它们转换为list
:
d = {'firstKey': 1708, 'secondKey': 1589, 'thirdKey': 1424}
print(list(d.keys()))
print(list(d.values()))
OUTPUT: OUTPUT:
['firstKey', 'thirdKey', 'secondKey']
[1708, 1424, 1589]
Try list(dict.keys())
and list(Counter.values())
尝试list(dict.keys())
和list(Counter.values())
>>> counter= Counter({'firstKey': 1708, 'secondKey': 1589, 'thirdKey': 1424})
>>> Keys = list(counter.keys())
>>> Keys
['firstKey', 'secondKey', 'thirdKey']
>>> Vals = list(counter.values())
>>> Vals
[1708, 1589, 1424]
>>>
Cast list()
to the dictionary to get the keys in a list, and cast list()
to the dict.values()
to get the values in a list:将list()
转换为字典以获取列表中的键,并将list()
转换为dict.values()
以获取列表中的值:
>>> from collections import Counter
>>> d = Counter({'firstKey': 1708, 'secondKey': 1589, 'thirdKey': 1424})
>>> l1 = list(d)
>>> l1
['firstKey', 'secondKey', 'thirdKey']
>>> l2 = list(d.values())
>>> l2
[1708, 1589, 1424]
Could also usedict.keys()
:也可以使用dict.keys()
:
>>> l1 = list(d.keys())
>>> l1
['firstKey', 'secondKey', 'thirdKey']
But not really needed since list(d)
will give you the keys by default.但实际上并不需要,因为list(d)
默认会为您提供密钥。
You could assign the two list variables in one line like this:您可以像这样在一行中分配两个列表变量:
d = Counter({'firstKey': 1708, 'secondKey': 1589, 'thirdKey': 1424})
keys,values = map(list,zip(*d.items()))
output: output:
print(keys)
print(values)
['firstKey', 'secondKey', 'thirdKey']
[1708, 1589, 1424]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.