3

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.

  • 1
    What do you expect as output? Dictionary keys can't be duplicated. – Austin Jun 15 '19 at 05:26
  • 1
    Look at this: [Convert 2 lists into dictionary](https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary-in-python) – Shadowfax Jun 15 '19 at 05:29
  • 3
    Possible duplicate of [Convert two lists into a dictionary in Python](https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary-in-python) – Anton vBR Jun 15 '19 at 05:31
  • I have come from that page only.. I just tried this out and it didn't work, so I asked it here.. – a_faulty_star Jun 15 '19 at 06:01

1 Answers1

4

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'
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80