Could anyone explain how this dict comprehension works?

This is the task i am on: https://www.codecademy.com/courses/learn-python-3/lessons/dictionaries-introduction/exercises/list-comp-to-dict

I don’t really understand the explanation codeacadamy has for list comprehensions, and was wondering if anyone could explain this simpler?
Could anyone explain how this syntax works?

students = {key:value for key, value in zip(names, heights)}
students = {key:value for key, value in zip(names, heights)}

zip(names, heights)
creates a zip object that gives you one tuple at a time …

the first tuple would be (names[0], heights[0]) ,
then next would be (names[1], heights[1])
and so on.

for key, value in
assigns key to represent the first thing in the tuple, and assigns value to be the second thing in the tuple
similar to

key = tuple[0]
value = tuple[1]

{ key: value
sets what’s in key to be a key in the dictionary and sets value to be the value for that key.

Overall, this sets the stuff in names to be the keys, and the stuff in heights to be the values of the dictionary students.

 

If you wanted to do the same using the indices, you could write

students = { names[i]: heights[i] for i in range(len(names)) }
2 Likes

Thank you for the answer, you explained it very well :smile: