Min value from a counter result in python

Viewed 6815

I'm new to programming and I find myself in some trouble. I have a list, and I want to know how many times an item shows up and then print the minimum value that shows up. So if I have A=[1e, 2b, 3u, 2b, 1e, 1e, 3u, 3u], I want to show something like "What you want is a 2", where 2 is the least amount of times something shows up, in this case 2b is the one that shows up the least amount of times. This is my code so far:

import collections

collections.Counter(A)
B = {key: value for (key, value) in A}
result = []
min_value = None
minimum = min(B, key=B.get)
print(minimum, B[minimum])

The output for this is 2b, but what I want the amount of times 2b shows up, since it is the one that shows up the least. I'm having some difficulty with this. To clarify, I want the minimum number in a counter result.

Any help would be appreciated, I'm sorry if my question is confusing English is not my first language and it's my first time doing something like this.

3 Answers

Just use min on dict.items, where dict is a Counter object:

from collections import Counter
from operator import itemgetter

c = Counter(A)
min_key, min_count = min(c.items(), key=itemgetter(1))

Since dict.items returns a view of key-value pairs, you can unpack directly to min_key, min_count variables.

Your code is basically right... do you just have a typo in your first couple lines?

import collections

A = ['1e', '2b', '3u', '2b', '1e', '1e', '3u', '3u']
B = collections.Counter(A)
result = []
min_value = None
minimum = min(B, key=B.get)
print(minimum, B[minimum])  # prints "2b 2"

Why not simply :

from collections import Counter

A = ['1e', '2b', '3u', '2b', '1e', '1e', '3u', '3u']

c = Counter(A)
print(c.most_common()[-1])  # Print ('2b', 2)

Here is the documentation for most_common()


Edit (see comment of @Back2Basics)

most_common() has to sort all the items by value which at best is N Log(N). If you use min() then you only have to go through one pass of the array, so it's N.

Related