Count occurrences of each key in python dictionary

后端 未结 2 1566
误落风尘
误落风尘 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条回答
  • Use collections.Counter and its most_common method:

    from collections import Counter
    def predominant_sign(data):
        signs = Counter(k['sign'] for k in data if k.get('sign'))
        for sign, count in signs.most_common():
            print(sign, count)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题