Thread: Multiple Modes from Dictionary?

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2013
Posts
8
Rep Power
0

Multiple Modes from Dictionary?

Hey there, I wrote a code which prints the mode of some numbers entered by a user. The problem is, the code will not generate multiple numbers if there are multiple modes. Does anyone know how I would alter this code to fix this problem?

Code:
```c = 4

dict1 = {}

while c == 4:
x = input("Please enter a number: ")
if x.isdigit() == False:
break
if x in dict1:
dict1[x] += 1
if x not in dict1:
dict1[x] = 1

findmax = [(value, key) for key, value in dict1.items()]
print (max(findmax)[1])```
2. This logic might work. Untested.
Code:
```dict1 = {}

while True:
x = input("Please enter a single digit number: ")
if not x.isdigit():
break
if x in dict1:
dict1[x] += 1
else:
dict1[x] = 1

counts_of_mode = max(dict1.values())
print([key for (key, value,) in dict1.items() if value == counts_of_mode])```
3. No Profile Picture
Contributing User
Devshed Novice (500 - 999 posts)

Join Date
May 2009
Posts
653
Rep Power
39
the code will not generate multiple numbers if there are multiple modes
I have no idea what this means. If you want to find the number with the most entries, then you can do that at entry time. Note that this line of code possibly has a misplaced closing paren ")"
Code:
```print (max(findmax)[1])
***```
Code:
```dict1 = {}
max_num = 0
max_entries = 0
while True:
x = input("Please enter a number, or any other key to exit: ")
if x.isdigit() == False:
break
if x not in dict1:
dict1[x] = 0
dict1[x] += 1
if dict1[x] > max_entries:
max_entries = dict1[x]
max_num = x

print max_entries, max_num```
Last edited by dwblas; November 18th, 2013 at 03:08 PM.
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2013
Posts
8
Rep Power
0
Originally Posted by b49P23TIvg
This logic might work. Untested.
Code:
```dict1 = {}

while True:
x = input("Please enter a single digit number: ")
if not x.isdigit():
break
if x in dict1:
dict1[x] += 1
else:
dict1[x] = 1

counts_of_mode = max(dict1.values())
print([key for (key, value,) in dict1.items() if value == counts_of_mode])```

This does indeed work. Thank you!
5. In this line of code

print (max(findmax)[1])

findmax is a list of tuples [(counts, value), ... ]

Connor474 wants the value(s) associated with the greatest count.