How many items in a dictionary share the same value in Python

前端 未结 5 1553
小鲜肉
小鲜肉 2021-01-02 22:53

Is there a way to see how many items in a dictionary share the same value in Python?

Let\'s say that I have a dictionary like:

{\"a\": 600, \"b\": 75         


        
相关标签:
5条回答
  • 2021-01-02 23:37

    You could use itertools.groupby for this.

    import itertools
    x = {"a": 600, "b": 75, "c": 75, "d": 90}
    [(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]
    
    0 讨论(0)
  • 2021-01-02 23:37
    >>> a = {"a": 600, "b": 75, "c": 75, "d": 90}
    >>> d={}
    >>> for v in a.values():
    ...   if not v in d: d[v]=1
    ...   else: d[v]+=1
    ...
    >>> d
    {600: 1, 90: 1, 75: 2}
    
    0 讨论(0)
  • 2021-01-02 23:41

    When Python 2.7 comes out you can use its collections.Counter class

    otherwise see counter receipe

    Under Python 2.7a3

    from collections import Counter
    items = {"a": 600, "b": 75, "c": 75, "d": 90}    
    c = Counter( items )
    
    print(  dict( c.items() ) )
    

    output is

    {600: 1, 90: 1, 75: 2}

    0 讨论(0)
  • 2021-01-02 23:41
    >>> a = {"a": 600, "b": 75, "c": 75, "d": 90}
    >>> b = {}
    >>> for k,v in a.iteritems():
    ...     b[v] = b.get(v,0) + 1
    ...
    >>> b
    {600: 1, 90: 1, 75: 2}
    >>>
    
    0 讨论(0)
  • 2021-01-02 23:44

    Use Counter (2.7+, see below at link for implementations for older versions) along with dict.values().

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