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

Viewed 83

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!

3 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}

Something like this should do the trick:

>>> from collections import Counter
>>> counts = Counter([item for sublist in your_dict.values() for item in sublist])

If you don't want to import any libraries you can do as follows:

function_name = {'key1':['apple', 'orange'], 'key2':['orange', 'pear']}
foobar = {}
for key, value in function_name.items():
    for element in value:
        if element in foobar:
            foobar[element] += 1
        else:
            foobar[element] = 1
print(foobar)

You check if the value is already in the created dict 'foobar'. If it is you add its value by one. If its not, then you add the value as a key and define its value as one. :)

Related