python: get the most frequent value in a list of dictionaries

前端 未结 1 1436
盖世英雄少女心
盖世英雄少女心 2021-01-16 18:01

I have a list of dictionaries, having this shape:

xs = [ { \'date\': 1 }, { \'date\': 1 }, { \'date\': 2 }, { \'date\': 1 }, { \'date\': 4 }]
相关标签:
1条回答
  • 2021-01-16 18:53

    Use a collections.Counter() object to count each date:

    from collections import Counter
    
    date_counts = Counter(d['date'] for d in xs)
    most_common = {'date': date_counts.most_common(1)[0][0]}
    

    I've assumed you wanted to get the output in the form of a dictionary again here, but you could just use date_counts.most_common(1)[0][0] directly if all you were interested in is that date value.

    Demo:

    >>> from collections import Counter
    >>> xs = [{'date': 1}, {'date': 1}, {'date': 2}, {'date': 1}, {'date': 4}]
    >>> date_counts = Counter(d['date'] for d in xs)
    >>> {'date': date_counts.most_common(1)[0][0]}
    {'date': 1}
    
    0 讨论(0)
提交回复
热议问题