Why does the official solution have us iterating through my_dictionary.keys() rather than just my_dictionary?
Here is the code I wrote:
def add_ten(my_dictionary):
# cycle through my_dictionary:
for key in my_dictionary:
# increase value corresponding to key by 10
my_dictionary[key] += 10
return my_dictionary
And here is the official solution:
def add_ten(my_dictionary):
for key in my_dictionary.keys():
my_dictionary[key] += 10
return my_dictionary
The official solution seems to be using a dictionary method, when it is entirely unnecessary. Am I missing something?
Your code is perfectly acceptable. The default behaviour when looping over dictionaries is for the keys in the dictionary to be iterated over, so the two solutions are essentially identical. In other words, for key in my_dictionary is the exact same as for key in my_dictionary.keys(). Using the .keys() method can make your code clearer/more readable, but it’s not strictly necessary.
def add_ten(my_dictionary):
my_dictionary_plus_10 = {}
for key,value in my_dictionary.values():
my_dictionary_plus_10[key] = value + 10
return my_dictionary_plus_10
Gives me the error
Traceback (most recent call last):
File "script.py", line 10, in <module>
print(add_ten({1:5, 2:2, 3:3}))
File "script.py", line 4, in add_ten
for key,value in my_dictionary.values():
TypeError: 'int' object is not iterable
I’m curious as to why this doesn’t work, I thought you could iterate through multiple items
Remember that .keys() returns the keys of a dictionary, .values() returns the values of a dictionary, and .items() returns the key-value pairs of a dictionary. Can you spot your error?
If we are iterating through the keys how are we adding 10 to the values? I’m not understanding how we are getting the information of the values and then being able to add 10 to them if the solution code has use going through keys.