econ_gradstudent
econ_gradstudent

Reputation: 11

How to get multiple keys assoicated with one value in python dictionary

#mode of numbers
number_counts = {}
for number in numbers:
    if number in number_counts:
        number_counts[number] += 1
    else:
        number_counts[number] = 1

max_count=0
for number in number_counts:
    if number_counts[number] > max_count:
        max_count = number_counts[number]
        print('Mode: ', number)

        #allkeys = ''
        #if number_counts[number] == max_count:
            #allnumbers = allnumbers +" "+str(number)+","
            #print('Mode: ', [allnumbers])

Here is the section of code that I am trying to fix. I am trying to find the mode of a list of numbers (coded as numbers earlier in my program). I have got it to give me one mode, but not all of them. I commented out what I thought might on the right track based on other posts.

Upvotes: 0

Views: 239

Answers (2)

Rory Daulton
Rory Daulton

Reputation: 22564

Your program prints a number as a mode only when the value of max_count is changed, which itself happens only when it finds a key with a larger count. If a key with the same count is encountered, it is ignored and you never see it printed. This is due to the line if number_counts[number] > max_count:--it should be if number_counts[number] >= max_count:.

However, your routine has another problem: it prints possible modes before it is sure they are modes--a number is printed if it has the largest count so far, not the largest count overall.

So change your final section that tries to print the mode into two sections (the code starting with max_count=0). The first part finds the value of max_count but cannot be sure what that is until the first section is finished. The second part then finds all numbers with that count and prints them.

By the way, that first part can be done in just one line:

max_count = max(number_counts.values())

There are other ways to find the modes, but this seems to be an exercise for you.

Upvotes: 1

cjhanks
cjhanks

Reputation: 544

If you are simply trying to one mode, that's relatively easy.

from collections import Counter

A = [0, 1, 2, 3, 4, 1, 1]
counts = Counter(A)

(mode, count) = counts.most_common(1)[0]

If you are really trying to map a dict of values, you would probably do something like.

from collections import defaultdict

counts = {
    0: 1,
    1: 1,
    2: 3,
    3: 1,
}

results = defaultdict(list)
for (number, value) in counts.items():
    results[value].append(number)

Upvotes: 0

Related Questions