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:
{'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
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:
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. Here, vals
is the list of tuples.
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}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.