Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Counter: print key whose count is x

Tags:

python

Say I have a Counter object representing a collection of words:

>>> words = ['hello', 'hello', 'hello', 'world']
>>> counter = Counter(words)

One way to find out which words have count 1 would be to iterate over counter:

for word, count in counter.items():
    if count == 1:
        print(word)

Is there an easier/better way to do this? That is, can one "invert" counter to give the word whose count is x?

like image 808
rookie Avatar asked Aug 12 '14 22:08

rookie


2 Answers

It would be far better to put every element with value 1 in a list, I think. Here's a Pythonic way to do this:

new_list = [w for w in words if counter[w] == 1]

Like this, you will store every word in words that has value of 1 in your counter.

So, for example, if you have in your list another string, say the string test:

words = ['hello', 'hello', 'hello', 'world', 'test']

then, the new list will have the values world and test.

like image 26
Belphegor Avatar answered Oct 02 '22 20:10

Belphegor


To reverse any mapping—whether a Counter, a dict, or anything else:

rev = {v: k for k, v in d.items()}

Then you use that like any other dictionary:

key_whose_count_is_10 = rev[10]

In the case where there are two keys with the same value, the value will map to one of them, arbitrarily. But that's pretty much inherent in your problem. You're asking for "the" key whose count is x; what do you want to do if there are three keys whose count is x?


If you're only going to be making one query, rather than multiple queries, it's more efficient to just iterate. Which one is clearer (which is almost always more important) is arguable. Here's one way to do it, for comparison:

key_whose_count_is_10 = next(k for k, v in d.items() if v==10)
like image 168
abarnert Avatar answered Oct 02 '22 18:10

abarnert