5

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?

Wouter
  • 534
  • 3
  • 14
  • 22
Diolor
  • 13,181
  • 30
  • 111
  • 179

2 Answers2

7

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
6

The easiest way is to simply use dict()

dict(Counter('abracadabra').most_common(3))

Output:

{'a': 5, 'r': 2, 'b': 2}
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40