Search code examples
pythondictionarypython-collections

Make Counter.most_common return dictionary


I used the sample from the documentation:

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

How can I make the result to be:

{ 'a': 5, 'r' :2 , 'b' :2}

supposing that we want to keep the Counter().most_common() code?


Solution

  • dict will do this easily:

    >>> dict(Counter('abracadabra').most_common(3))
    {'a': 5, 'r': 2, 'b': 2}
    >>>
    

    For further reference, here is part of what is returned by help(dict):

         dict(iterable) -> new dictionary initialized as if via:
     |      d = {}
     |      for k, v in iterable:
     |          d[k] = v