user2741700
user2741700

Reputation: 901

Counter to List

I have a counter like this :

counter = Counter(['a','a','b','b','b','c'])

which gives this object :

Counter({'b': 3, 'a': 2, 'c': 1})

and from that I want to creat a list such as :

list[0] = 'b'
list[1] = 'a'
list[2] = 'c'

any idea to do that the simpliest and fastest way possible please ? thanks

Upvotes: 13

Views: 22534

Answers (5)

dawg
dawg

Reputation: 103754

You could do this:

from collections import Counter
import operator

counter = Counter(['a','a','b','b','b','c'])
print [k for k,v in sorted(counter.iteritems(), key=operator.itemgetter(1), reverse=True)]
# ['b', 'a', 'c']

Or, better still:

from collections import Counter

counter = Counter(['a','a','b','b','b','c'])
print [k for k,v in counter.most_common()]

Upvotes: 0

falsetru
falsetru

Reputation: 368954

You can use collections.Counter.most_common (which returns a list of the n most common elements and their counts from the most common to the least):

>>> counter.most_common()
[('b', 3), ('a', 2), ('c', 1)]

>>> [key for key, _ in counter.most_common()]
['b', 'a', 'c']

Upvotes: 16

shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13372

Simplest (IMO) method as told by falsetru

sorted(counter, key=counter.get, reverse=True)

The above would sort the counter dict based on the values of the keys (.get()) & return a reversed list.

Upvotes: 5

Back2Basics
Back2Basics

Reputation: 7806

if you want to skip the steps you can type.

list(set(['a','a','b','b','b','c']))

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You can cast it to a list, but it will not keep the order you want since dictionaries are unsorted:

list1 = list(counter)

Upvotes: 3

Related Questions