Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min value from a counter result in python

Tags:

python

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.

like image 262
Malsum Avatar asked Oct 16 '22 11:10

Malsum


People also ask

How do you find the min value in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.

What does Counter () do in Python?

Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.

What is collections Counter () in Python?

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.


1 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.

like image 104
jpp Avatar answered Dec 01 '22 19:12

jpp