[英]Creating a nested dictionary from tuples that counts the number of occurrences of a tuple item
I have to sort through a list of tuples and create a dictionary with the first item in the tuple as a key and nested dictionaries which would have the key as the second item and the number of occurrences as the value.我必须对元组列表进行排序并创建一个字典,其中元组中的第一项作为键,嵌套字典将键作为第二项,出现次数作为值。 I'm not sure how to approach this problem and any help would be fantastic.
我不确定如何解决这个问题,任何帮助都会很棒。
[('academic', 'hacked'), ('academic', 'lost device'), ('academic', 'lost device'), ('academic', 'lost device'), ('energy', 'inside job'), ('financial', 'hacked')]
Desired output:所需的 output:
{'academic': {'lost device': 3, 'hacked': 1}, 'energy': {'inside job': 1}, 'financial': {'hacked': 1}}
It's not the pythonic way to do it, but at least it's working这不是pythonic的方式,但至少它正在工作
mylist = [('academic', 'hacked'), ('academic', 'lost device'), ('academic', 'lost device'), ('academic', 'lost device'), ('energy', 'inside job'), ('financial', 'hacked')]
dict = {}
for el in mylist:
if not el[0] in dict.keys():
dict[el[0]] = {}
if not el[1] in dict[el[0]].keys():
dict[el[0]][el[1]] = 1
else:
dict[el[0]][el[1]] += 1
print (dict)
As a result I get:结果我得到:
{'academic': {'hacked': 1, 'lost device': 3}, 'energy': {'inside job': 1}, 'financial': {'hacked': 1}}
Use setdefault
- it is nice:使用
setdefault
- 这很好:
x={}
for a,b in mylist:
c=x.setdefault(a,{})
c[b]=c.setdefault(b,0)+1
print(x)
You can do this in a single line using Collections.Counter
as follows.您可以使用
Collections.Counter
在一行中执行此操作,如下所示。 Here, vals
is the list of tuples.这里,
vals
是元组列表。
from collections import Counter
dict((k[0],{k[1]:v})for k, v in Counter(vals).items())
from collections import Counter
vals = [('academic', 'hacked'), ('academic', 'lost device'), ('academic', 'lost device'),
('academic', 'lost device'), ('energy', 'inside job'), ('financial', 'hacked')]
output = dict((k[0],{k[1]:v})for k, v in Counter(vals).items())
print(output)
Result :结果:
{'academic': {'hacked': 1, 'lost device': 3}, 'energy': {'inside job': 1}, 'financial': {'hacked': 1}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.