Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list of frequencies for a certain value in a dict

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!

like image 361
Emma Pascoe Avatar asked Nov 01 '18 19:11

Emma Pascoe


Video Answer


1 Answers

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}
like image 183
timgeb Avatar answered Sep 28 '22 03:09

timgeb