Home > front end >  How do I separetly print two dictionary keys with the same value?
How do I separetly print two dictionary keys with the same value?

Time:12-09

I want to print a message telling the user the most common personality type of an animal crossing villager using a dataset. However, the 'Lazy' and 'Normal' dictionary keys are both the most common and have the same value. I can't figure out how to make them print separately without hardcoding.

Here's my code:

totalfreq2 = {}

for p_type in personality:
  if p_type in totalfreq2:
    totalfreq2[p_type]  =1
  else:
    totalfreq2[p_type] = 1
print(totalfreq2)

maxfreq2 = max(totalfreq2.values())
print(maxfreq2)
toplst = ()
for p_type in totalfreq2:
  if totalfreq2[p_type] == 63:
    ww = p_type
print(ww)
print("The most common personality type for an Animal Crossing Villager is",ww,)

Here's the printed output:

{'Jock': 57, 'Cranky': 57, 'Peppy': 53, 'Big Sister': 26, 'Lazy': 63, 'Normal': 63, 'Snooty': 57, 'Smug': 37}
63
Normal
The most common personality type for an Animal Crossing Villager is Normal

How do I add 'Lazy' to this message without hardcoding?

CodePudding user response:

Collect all the keys that have the max value, then use .join() to print them nicely:

# The missing data matching the OP's output.
personality = ['Jock'] * 57   ['Cranky'] * 57   ['Peppy'] * 53   ['Big Sister'] * 26   ['Lazy'] * 63   ['Normal'] * 63   ['Snooty'] * 57   ['Smug'] * 37

totalfreq2 = {}

for p_type in personality:
  if p_type in totalfreq2:
    totalfreq2[p_type]  =1
  else:
    totalfreq2[p_type] = 1

maxfreq2 = max(totalfreq2.values())
# find all keys with same max value
toplist = [k for k,v in totalfreq2.items() if v == maxfreq2]
print(f"The most common personality type for an Animal Crossing Villager is: {', '.join(toplist)}")

Output:

The most common personality type for an Animal Crossing Villager is: Lazy, Normal

See also collections.Counter for a built-in way to count items and get the most common, for example:

import collections
...
totalfreq2 = collections.Counter(personality)
# Returns counts sorted highest to lowest and gets the first one.
# It returns [(key, count)] hence the subscripting to get the count.
maxfreq2 = totalfreq2.most_common(1)[0][1]
...

CodePudding user response:

It looks like you had the right idea... just change toplist to an empty list and instead of assigning the value to the variable ww you can append the value to the list and then print the contents of the list once the loop has finished.

maxfreq2 = max(totalfreq2.values())
toplst = []
for p_type in totalfreq2:
  if totalfreq2[p_type] == maxfreq2:
    toplst.append(p_type)
print(toplst)

There are quite a few alternatives you could use as well.

list comprehension.

[print(i) for i in totalfreq2 if totalfreq2[i] == maxfreq2]

or you can use the filter function

for ptype in filter(lambda x: totalfreq2[x] == maxfreq2, totalfreq2.keys()):
    print(ptype)
  • Related