Max get() method explanation



I'm working on a program that reports the number of times a character occurs in a string. It then adds that character and its count as an entry to a dictionary. To retrieve the character with the highest count, I am using:

d = {}
mary = "Mary had a little lamb"
for x in mary:
	y = mary.count(x)
	d[x] = y
print("The max element is", max(d, key=d.get))

The code works fine, but I don't understand how max is working to find the maximum value. The documentation on get seems to indicate that it retrieves the value of the key you indicate for it, as such:


But in my code, I am receiving the key.

Could someone explain to me how this is working in the code I have?


i don't see why you use get, get will give you the corresponding value of a key if you provide the key as argument, which is what you do here:


the parentheses which contains the argument, are missing in your case, what i simply would do is use values() which will give you a view of the dictionary, and get the maximum:


but i guess then you need to know the key as well?


Yes, need to retrieve the key with the highest corresponding value. The code I have works, but I don't understand why this works.


well, you seem to be using get() wrong, and i put your code here, it doesn't seem to be working? Where did you manage to get it to work?


I'm running it in Idle, for version 3.5.2. I think its returning white space.

Add this after the print("The max element is", max(d, key=d.get)):

del d[max(d, key=d.get)]
("The max element is", max(d, key=d.get))


it still feels really unreliable, maybe a different approach? I found a stackoverflow where people are struggling with the exact same problem:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.