Question

I have a dictionary consisting of key: value(list). I would like to do a frequency count of the first element in the list inside the dictionary.

An example of how the dictionary looks like:

dict_id = {'id_111': ['10'], 'id_222': ['10', '10'], 'id_234': ['9'], 'id_654': ['13', '10'], ..}

Desired results:

[(['10'], 2), (['9'], 1), (['13'], 1), ...]

This is what I have tried but it's using the entire list as key instead of the first element in the list.

newDict = [(k, len(list(v))) for k, v in itertools.groupby(ids.values())]
print newDict

>> [(['10'], 1), (['10', '10'], 1), (['13', '10'], 1), ...]

Any help is appreciated.

Was it helpful?

Solution 2

newDict = {}
for k, v in dict_id.iteritems():
    if v[0] in newDict:
        newDict[v[0]] += 1
    else:
        newDict[v[0]] = 1
print newDict

This will create an actual dictionary though.

OTHER TIPS

from collections import Counter
print Counter(dict_id[k][0] for k in dict_id)
# Counter({'10': 2, '9': 1, '13': 1})

If you want the output to be in the format you specified in the question

print [([k], c) for k, c in Counter(dict_id[k][0] for k in dict_id).items()]
# [(['9'], 1), (['10'], 2), (['13'], 1)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top