Reputation: 37
I am relatively new to Python, and I need some help to understand how the output is obtained for the following code:
keys = ['id', 'name', 'age']
values = [10, 'Ross', 19]
a_dict = {key:value for key in keys for value in values}
print(a_dict)
The output is:
{'id': 19, 'name': 19, 'age': 19}
I have tried nested loop too and I got the same output. I also tried interchanging key and value in the loop but there was no effect.
Can someone explain this please?
Edit:
I know how to get the output as
{'id': 10, 'name': 'Ross', 'age': 19}
I am only requesting an explanation for how the code I wrote works.. especially how the for loop works for the value part.
Upvotes: 3
Views: 66
Reputation: 36652
You need to iterate simultaneously on both list, in order to pair the values with the keys:
keys = ['id', 'name', 'age']
values = [10, 'Ross', 19]
a_dict = {key:value for key, value in zip(keys, values)}
print(a_dict)
output:
{'id': 10, 'name': 'Ross', 'age': 19}
zip
pairs the keys and the values in a tuple (key, value)
. key, value = (key, value)
key: value
By comparison, the code you wrote a_dict = {key:value for key in keys for value in values}
does:
'id': 10, 'name': 10, 'age': 10'
'id': 'Ross', 'name': 'Ross', 'age': 'Ross'
'id': 19, 'name': 19, 'age': 19'
Upvotes: 4