a_faulty_star
a_faulty_star

Reputation: 37

Explanation of dictionary creation

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

Answers (1)

Reblochon Masque
Reblochon Masque

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}

What is happening?

  • zip pairs the keys and the values in a tuple (key, value).
  • then the pair is "unpacked" and assigned: key, value = (key, value)
  • finally, the dictionary entry is built: key: value
  • this is repeated for each pair in the input.

The code you wrote:

By comparison, the code you wrote a_dict = {key:value for key in keys for value in values} does:

  • iterates over the keys.
  • then, for each key, iterates over the values.
  • for each key, assigns each value in succession, each time overwriting the values already assigned, and terminating with the last value assigned to all the keys, that is:
    'id': 10, 'name': 10, 'age': 10'
    'id': 'Ross', 'name': 'Ross', 'age': 'Ross'
    'id': 19, 'name': 19, 'age': 19'

Upvotes: 4

Related Questions