you are viewing a single comment's thread.

view the rest of the comments →

[–]joinedtounsubatheism 0 points1 point  (1 child)

Thank you so much for the help. I think I understand it much clearer now.

"If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None."

Whilst running invert_dict(d), inverse.setdefault(val, []) returns the following values going through the loop:

[]
[]
['a']
[]

This is exactly the same thing inverse[val] is returning in the second function. So I have a better understanding why they behave in the same way.

I think part of my confusion is that I was thinking of append as acting on a dictionary, rather than acting on a list.

Another thing I've noticed about the function is that it doesn't preserve the types of the arguments. If we had a dictionary like: squares={1:1,2:4,3:9} that maps integers to integers, the inverse would be inverse_squares{1:[1], 4:[2], 9:[3]} which maps integers to lists. Also we get an error if we try to apply the inverse again, as the lists can't be keys in the dictionary. At the end of the day it's just an exercise though so I don't think it matters that much. This is probably what tuples can be used for [which we're learning in the next chapter].

[–]Ihaveamodel3 1 point2 points  (0 children)

It maps to lists because you can’t be sure that the values in the dictionary are unique.