Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find least frequent value in dictionary

I'm working on a problem that asks me to return the least frequent value in a dictionary and I can't seem to work it out besides with a few different counts, but there aren't a set number of values in the dictionaries being provided in the checks.

For example, suppose the dictionary contains mappings from students' names (strings) to their ages (integers). Your method would return the least frequently occurring age. Consider a dictionary variable d containing the following key/value pairs:

{'Alyssa':22, 'Char':25, 'Dan':25, 'Jeff':20, 'Kasey':20, 'Kim':20, 'Mogran':25, 'Ryan':25, 'Stef':22}

Three people are age 20 (Jeff, Kasey, and Kim), two people are age 22 (Alyssa and Stef), and four people are age 25 (Char, Dan, Mogran, and Ryan). So rarest(d) returns 22 because only two people are that age.

Would anyone mind pointing me in the right direction please? Thanks!

like image 241
jlee Avatar asked Dec 11 '22 09:12

jlee


2 Answers

Counting the members of a collection is the job of collections.Counter:

d={'Alyssa':22, 'Char':25, 'Dan':25, 'Jeff':20, 'Kasey':20, 'Kim':20, 'Mogran':25, 'Ryan':25, 'Stef':22}
import collections
print collections.Counter(d.values()).most_common()[-1][0]
22
like image 64
Robᵩ Avatar answered Jan 06 '23 18:01

Robᵩ


You can create an empty dict for the counters, then loop through the dict you've got and add 1 to the corresponding value in the second dict, then return the key of the element with the minimum value in the second dict.

like image 30
jazzpi Avatar answered Jan 06 '23 16:01

jazzpi