Search code examples
pythonlistdictionarykeytuples

Count how many times a part of a key appears in a dictionary python


I have the following dictionary and i want to count how many times keys appear, dictionary is very big.

a = { (1,2):3, (1,3):5, (2,1):6 }

and I want this result

1: 3 times
2: 2 times
3: 1 time

Solution

  • >>> from collections import Counter
    >>> a = { (1,2):3, (1,3):5, (2,1):6 }
    >>> 
    >>> Counter(j for k in a for j in k)
    Counter({1: 3, 2: 2, 3: 1})