Reputation:
I have a nested dictionary:
{'1': {'Toy Story (1995)': 5.0,
'GoldenEye (1995)': 3.0,
'Four Rooms (1995)': 4.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0},
'2': {'GoldenEye (1995)': 3.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0},
'3': {'Toy Story (1995)': 5.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0}}
As you see I have three items and for each as values there are dictionaries with films. I want to count which films appear most often. So the output can be a list or dictionary with movie name and how often it appeared among items. Like:
{'Get Shorty (1995)': 3,
'Copycat (1995)': 3,
'GoldenEye (1995)': 2,
'Toy Story (1995)': 2,
'Four Rooms (1995)': 1}
How to do that?
Upvotes: 1
Views: 196
Reputation: 300
To get the desired result we can first iterate through all the keys in the given dictionary and extract their value and then from those values, we will again iterate to get their keys and add them to our new dictionary as key and then increase their value as they reoccur.
The code i tried is
sample_dict = {'1': {'Toy Story (1995)': 5.0,
'GoldenEye (1995)': 3.0,
'Four Rooms (1995)': 4.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0},
'2': {'GoldenEye (1995)': 3.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0},
'3': {'Toy Story (1995)': 5.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0}}
result_dict= {}
for key in sample_dict.keys():
for keys in sample_dict[key].keys():
if keys in result_dict.keys():
result_dict[keys] += 1
else:
result_dict[keys] = 1
print(result_dict)
Upvotes: 0
Reputation:
how about this?
org_dict = {'1': {'Toy Story (1995)': 5.0,
'GoldenEye (1995)': 3.0,
'Four Rooms (1995)': 4.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0},
'2': {'GoldenEye (1995)': 3.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0},
'3': {'Toy Story (1995)': 5.0,
'Get Shorty (1995)': 3.0,
'Copycat (1995)': 3.0}}
new_dict = {}
for e in org_dict.values():
for movie in e.keys():
if movie in new_dict:
new_dict[movie] += 1
else:
new_dict[movie] = 1
new_dict
output is
{'Copycat (1995)': 3,
'Four Rooms (1995)': 1,
'Get Shorty (1995)': 3,
'GoldenEye (1995)': 2,
'Toy Story (1995)': 2}
Upvotes: 0
Reputation: 21619
Use itertools.chain.from_iterable
to flatten just the movie names into one long list and then collections.Counter
to count the repeated names.
Assuming your nested dict is called x
.
>>> from itertools import chain
>>> from collections import Counter
>>> Counter(chain.from_iterable(x.values()))
Counter({'Get Shorty (1995)': 3, 'Copycat (1995)': 3, 'Toy Story (1995)': 2, 'GoldenEye (1995)': 2, 'Four Rooms (1995)': 1})
You can convert the Counter back to a regular dict
using
dict(counter)
Assuming your Counter is named counter
.
Upvotes: 7