A Problem with dictionaries | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

A Problem with dictionaries

I have a list of numbers from 1 to 4 those numbers are repeated and I need to find a way to return the number that's repeated the most, but if there is a case where a number repeats the same amount as some other number then I need to return that which is greater. So I thought a dictionary could be a good way to work, and I found some code on geek, but I don't understand what they are doing, so it's hard to adapt to my case, that's where I need help. https://code.sololearn.com/cA23a10A23a1/?ref=app

10th Jun 2021, 3:02 PM
Jace🎭
Jace🎭 - avatar
4 Answers
+ 2
# line 8: yes, count = 0, itm = "", it's just written in the same line (tuple unpacked) # line 10: for each item, increase the counter (value) of this item in the dict, that's +1 # in your dict, the key (dict[item]) is the name of the element, the value is the counter (how often the item is in the list) # I would recomment you, not to name variables list or dict, because they might overwrite the built-in functions list() and dict()
10th Jun 2021, 3:28 PM
Lisa
Lisa - avatar
+ 2
1. Yes, line 8 is a single line assignment of count and itm. 2. On line 10, the get method of a dictionary returns a value of the specified key, if the key is non existent, the second parameter is returned (0 in this case). Because the dictionary is initially empty, 0 is returned and the key is assigned and incremented by 1. This is done to keep track of how many times the value appears in the list. 3. Yes, remember item is our dictionary key. This code will keep track of how many times a key appears in the list and return the key that appears the most. It won't, however, break a tie if there are keys with equal frequency and return the bigger number. I have modified the code with a tie breaking algorithm. https://code.sololearn.com/c48r6qBwiRCq/?ref=app
10th Jun 2021, 3:54 PM
CouldntBeBothered.py
CouldntBeBothered.py - avatar
+ 2
https://code.sololearn.com/cNX2Tbz4d2c4/?ref=app thats a pythonic alternative
10th Jun 2021, 6:02 PM
Oma Falk
Oma Falk - avatar
+ 1
Michael # dict[item] it's our counter, [item] is the key we are checking and adding the value if the same key is repeated the next cycle #count is used to compared to the previous key that's repeated the most? #"itm" has a record of the list we are in and saves the ones that are repeated the most in a new list to later check if what's the max value in list
10th Jun 2021, 6:16 PM
Jace🎭
Jace🎭 - avatar