What is the point of dict method list vs. just calling the dict?

available_items = {“health potion”: 10, “cake of the cure”: 5, “green elixir”: 20, “strength sandwich”: 25, “stamina grains”: 15, “power stew”: 30}

reversed = {value: key for key, value in available_items.items()}

https://www.codecademy.com/paths/data-analyst/tracks/dsf-python-fundamentals-for-data-science-part-ii/modules/dsf-python-dictionaries/lessons/using-dictionaries/exercises/pop-a-key

If I want to use dict comprehension to reverse the key:value pairs, I must call dict.list() method. Otherwise, it returns “too many values to unpack”, despite the dict being 1:1. But wouldn’t the “for” iterate over the dict already?

Hello @notvines9244142638!

If I understand you correctly, you are trying to run two lines of code (I added the third for showing the output):

available_items = {"health potion": 10, "cake of the cure": 5, "green elixir": 20, "strength sandwich": 25, "stamina grains": 15, "power stew": 30} reversed = {value: key for key, value in available_items.items()} print(reversed)

Unfortunately, they run just fine in the codebyte, the codecademy.com environment and my local Python prompt. Could you provide more information on your problem?

What exactly do you mean by “I must call dict.list() method”? According to the Python Documentation on dicts dict.list() returns a list of all the keys used in the dictionary d. How does that help you solve your problem?

1 Like

If I understand you correctly: Yes, you need dict.items() to perform this comprehension because simple iteration over the dictionary itself (such as with a for loop) only iterates over the keys of the dictionary. Some examples:

dictionary = {'a': 1, 'b': 2, 'c': 3} # Prints a, b, c for x in dictionary: print(x) # Prints (a, 1), (b, 2), (c, 3) for y in dictionary.items(): print(y) # Unpacks the key,value tuples given by the .items() method into seperate variables for key, value in dictionary.items(): print(f"Key: {key}, Value: {value}") # This one fails try: for key, value in dictionary: print(f"Key: {key}, Value: {value}") except Exception as e: print(e)

the items() method gives you access to the (key, value) tuples that allow you to perform the value: key for key, value unpacking in the dict comprehension you have.