Python Code Challenges: Dictionaries

Hello!
I’m currently on challenge 5 of codecademys coding challenges for dictionaries. Challenge 5 asks to write a code that will return the key with the largest value. Below is my code where I attempted to:
1.) Create a list of all the values
2.) Sort the list
3.) Save the last (and therefore largest) element of that list to a variable
4.) Iterate through the dictionaries values and compare them to the largest number
5.) Return the key if the values are a match

# Write your max_key function here: def max_key (my_dictionary): list_ = list([my_dictionary.values()]) list_.sort() largest_number = list_[-1] for key in my_dictionary: if my_dictionary[key] == largest_number: print(key) # Uncomment these function calls to test your function: print(max_key({1:100, 2:1, 3:4, 4:10})) # should print 1 print(max_key({"a":100, "b":10, "c":1000})) # should print "c"

But when I run this code I get ‘None’ printed to the terminal. Could someone explain what is wrong with my code?

What is this line doing?
list_ = list([my_dictionary.values()])

Try printing list_ to see if what you have is what you thought you’d have.

That line was meant to create a list of the values of the dictionary, but when I print list_ I get [dict_values([100, 1, 4, 10])] and [dict_values([100, 10, 1000])]. My new attempt:

# Write your max_key function here: def max_key(my_dictionary): empty_list = [] for key in my_dictionary: empty_list.append(my_dictionary[key]) empty_list.sort() largest_number = empty_list[-1] for key in my_dictionary: if my_dictionary[key] == largest_number: print(key) # Uncomment these function calls to test your function: print(max_key({1: 100, 2: 1, 3: 4, 4: 10})) # should print 1 print(max_key({"a": 100, "b": 10, "c": 1000})) # should print "c"

It works (kinda)! When I run the code it returns what I want, but it also returns ‘None’.

For the record, list(dic.vlaues()) will work as expected. What was pointed out is the [..] syntax in the first example.

>>> d = {
	'one': 1,
	'two': 2,
	'three': 3
	}
>>> [*d.values()]
[1, 2, 3]
>>> list(d.values())
[1, 2, 3]
>>> l = list(d.values())
>>> l
[1, 2, 3]
>>> 

Just be sure not to put the dictionary inside a list literal.

1 Like

Which is expected behavior. Your function prints key, and returns None which is then printed on lines 14 and 16. In the absence of an explicit return statement, python functions implicitly return None.

1 Like