Count occurrences of each key in python dictionary

后端 未结 2 1583
误落风尘
误落风尘 2021-01-04 00:26

I have a python dictionary object that looks somewhat like this:

[{\"house\": 4,  \"sign\": \"Aquarius\"},
 {\"house\": 2,  \"sign\": \"Sagittarius\"},
 {\"h         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 01:02

    You can use collections.Counter module, with a simple generator expression, like this

    >>> from collections import Counter
    >>> Counter(k['sign'] for k in data if k.get('sign'))
    Counter({'Sagittarius': 2, 'Capricorn': 2, 'Aquarius': 2, 'Leo': 2, 'Scorpio': 1, 'Gemini': 1}) 
    

    This will give you a dictionary which has the signs as keys and their number of occurrences as the values.


    You can do the same with a normal dictionary, like this

    >>> result = {}
    >>> for k in data:
    ...     if 'sign' in k:
    ...         result[k['sign']] = result.get(k['sign'], 0) + 1
    >>> result
    {'Sagittarius': 2, 'Capricorn': 2, 'Aquarius': 2, 'Leo': 2, 'Scorpio': 1, 'Gemini': 1}
    

    The dictionary.get method, accepts a second parameter, which will be the default value to be returned if the key is not found in the dictionary. So, if the current sign is not in result, it will give 0 instead.

提交回复
热议问题