Hi everyone:
I’ve seen this question asked before, but the answer was, "actually, that’s not the result you’re getting. But… it is! When I run the code shown below, print(names_to_ages) returns “{}” instead of the populated dictionary.
Can anyone please tell me what I’m doing wrong? I got frustrated with it and copied the code directly from the “hint” text, but i still get the same answer. Tried copying from the solutions too, but had the same problem.
I think another way to put it is that zip consumes itself when it combines the two lists (or iterables) and returns a zip object, which is why when you go to print it, you get something like:
zipped_ages = zip(names, ages)
print(zipped_ages)
<zip object at 0x7ff208c2d080>
So, when you go to use it a 2nd time, here" names_to_ages = {key: value for key, value in zipped_ages}
it’s already been “consumed” with the original zip() and there’s nothing to iterate over. So, you get nothing, or an empty dictionary. You have to cast it as a list().
because you’re iterating over the zipped object with a for loop.
print(zipped_ages) #prints nothing
names_to_ages = {key: value for key, value in zipped_ages} #this works b/c you're iterating over the zipped object
>>><zip object at 0x7ff208c2dfc0>
{'Marina': 27, 'Vinay': 24, 'Connie': 43, 'Isaac': 35, ' Valentina': 52}
Thank you! The problem came when I tried to print list(zipped_ages), but it worked as soon as I removed that line. I like the idea of setting it equal to a list of the zipped_ages when zipping them. I tried it in my code and it worked perfectly.
This: print(list(zipped_ages) doesn’t change the original zipped_ages. It just changes it in that piece of code (for lack of a better phrase. Sorry, I’m tired. lol).
So, when you comment out that piece, you end up iterating over that zipped object with your for loop and create the dictionary.