So I have a dict, which contains keys corresponding to a list, which contains str. I want to collect all the same values in said list and sum them together. Perhaps my explanation was confusing so I'll provide an example:
function_name({'key1':['apple', 'orange'], 'key2':['orange', 'pear'})
>>> {'apple':1, 'orange':2, 'pear':1}
How would I create this function? I was thinking of somehow making a for loop like this:
count = 0
for fruit in dict_name:
if food == 'apple'
count = count + fruit
I am still unsure about how to format this especially how to count the values and collect them, thanks in advance for any suggestions!
You can un-nest the dict's values and apply a Counter
.
>>> from collections import Counter
>>>
>>> d = {'key1':['apple', 'orange'], 'key2':['orange', 'pear']}
>>> Counter(v for sub in d.values() for v in sub)
Counter({'apple': 1, 'orange': 2, 'pear': 1})
If you don't like the nested generator comprehension, the un-nesting can be done with itertools.chain.from_iterable
.
>>> from itertools import chain
>>> Counter(chain.from_iterable(d.values()))
Counter({'apple': 1, 'orange': 2, 'pear': 1})
Without imports and with traditional loops, it would look like this:
>>> result = {}
>>> for sub in d.values():
...: for v in sub:
...: result[v] = result.get(v, 0) + 1
...:
>>> result
{'apple': 1, 'orange': 2, 'pear': 1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With