Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Counter keys() return values

Tags:

python

counter

I have a Counter that is already ordered by number of occurrences.

counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...}).

But when I do counterlist.keys() the return list is:

['wirespe', 'four', 'accus',...]

instead of

['they', 'would', 'your',...].

Why?

like image 841
user3005486 Avatar asked Jan 28 '16 20:01

user3005486


People also ask

How do I extract a value from a Counter in Python?

Accessing Elements in Python Counter To get the list of elements in the counter we can use the elements() method. It returns an iterator object for the values in the Counter.

What does Counter Python return?

Python Counter is a subclass of the dict or dictionary class . It keeps track of the frequency of each element in the container . It takes as argument an iterable object (like list) and returns back a dictionary.

What is collections Counter () in Python?

Counter is an unordered collection where elements are stored as Dict keys and their count as dict value. Counter elements count can be positive, zero or negative integers. However there is no restriction on it's keys and values. Although values are intended to be numbers but we can store other objects too.

How do you use counters in Python?

Initializing. Counter supports three forms of initialization. Its constructor can be called with a sequence of items, a dictionary containing keys and counts, or using keyword arguments mapping string names to counts. To create an empty counter, pass the counter with no argument and populate it via the update method.


1 Answers

Another solution without creating an extra class is to take the set of items you have and sort them based on the counted keys. The code below is based on @user3005486:

import collections

#if this is your list    
list_to_be_sorted = ['they', 'would', 'they', ...]
#then counterlist = {'would': 203, 'they': 138, 'your': 134}
counterlist = collections.Counter(list_to_be_sorted)
#if you sort this list ascendingly you get ['would', 'would', ..., 'they', 'they', ...etc.]
sorted_words = sorted(counterlist, key: lambda x:-counterlist[x])
distinct_words_from_list = set(list_to_be_sorted)
sorted_distinct_list = sorted(distinct_words_from_list, key: lambda x:-counterlist[x])
#then sorted_distinct_list = ['would', 'they', 'your']
like image 65
Bahaa Avatar answered Oct 01 '22 21:10

Bahaa