Reputation: 81
I'm working with dictionaries and was wondering how I could output a dictionary where its key is the word that occurs in a given dictionary and its value is the number of times it occurs within that dictionary.
So say for example,
A = {'#1': ['Yellow', 'Blue', 'Red'], '#2': ['White', 'Purple', 'Purple', 'Red']}
B - []
for key in A:
B.append(A[key])
>>> B
>>> [['Yellow', 'Blue', 'Red'], ['White', 'Purple', 'Purple', 'Red']]
After returning the respective values of the keys, I can now loop through each list of strings and flatten the list of values.
C = []
for sublist in B:
for item in sublist:
C.append(item)
I know that I need to count the number of times the certain strings occur in that list and then populate a dictionary with the key being the colour and the value being how many times it occurs. This part is mainly where I'm having difficulty.
Upvotes: 1
Views: 400
Reputation: 5660
You can use a Counter
object:
>>> from collections import Counter
>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']
>>> Counter(c)
Counter({'Red': 2, 'Purple': 2, 'Yellow': 1, 'Blue': 1, 'White': 1})
Or make your own:
>>> d = {i: c.count(i) for i in c}
>>> d
{'Yellow': 1, 'Blue': 1, 'Red': 2, 'White': 1, 'Purple': 2}
Also you can make your c
creation shorter:
c = []
for i in A.values():
c.extend(i)
>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']
or:
c = [j for i in A.values() for j in i]
>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']
Upvotes: 5