Max get() method explanation


#1

Hello,

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(d)
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:

d.get('a')
#4

But in my code, I am receiving the key.

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


#2

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:

d.get('a')

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:

print(max(d.values()))

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


#3

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


#4

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?


#5

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))

#6

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


#7

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