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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With