-1
dct = {k: v for k in ["HELLO", "SLEEPING"] for v in ["WORLD", "CITY"]}

print(dct["HELLO"])
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
lazer
  • 25
  • 2
  • Did you actually check the value of ``dct`` itself? Why would you assume that ``"World"`` is the value of *any* key in the end? – MisterMiyagi Jun 09 '20 at 08:39
  • 1
    Does this answer your question? [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – MisterMiyagi Jun 09 '20 at 08:41
  • 1
    If you create a list instead of a dict : `[(k,v) for k in ["HELLO", "SLEEPING"] for v in ["WORLD", "CITY"]]`, you'll see by yourself the nested loops that all the answers mention : `[('HELLO', 'WORLD'), ('HELLO', 'CITY'), ('SLEEPING', 'WORLD'), ('SLEEPING', 'CITY')]`. Makes it easier to understand why SLEEPING is "overwritten" in the dict case. – Demi-Lune Jun 09 '20 at 08:42

3 Answers3

2

you are overwriting the values. first you set both keys "HELLO" and "SLEEPING" to "WORLD", then you set them again both(!) to "CITY". see: https://stackoverflow.com/a/17006736/12693728

mrxra
  • 852
  • 1
  • 6
  • 9
2

This is what the comprehension looks like as multi like.

In [1]: {k: v for k in ["HELLO", "SLEEPING"] for v in ["WORLD", "CITY"]}                                                                             
Out[1]: {'HELLO': 'CITY', 'SLEEPING': 'CITY'}

In [2]: d = {}                                                                                                                                       

In [3]: for k in ["hello", "sleeping"]: 
   ...:     for v in ["world", "city"]: 
   ...:         d[k]=v 
   ...:                                                                                                                                              

In [4]: d                                                                                                                                            
Out[4]: {'hello': 'city', 'sleeping': 'city'}

What you want to do is zip the two lists

In [8]: {k: v for k,v in zip( ["HELLO", "SLEEPING"],["WORLD", "CITY"])}                                                                              
Out[8]: {'HELLO': 'WORLD', 'SLEEPING': 'CITY'}
Tonis F. Piip
  • 776
  • 2
  • 6
  • 16
0

You are iterating through both lists, so you will be initially mapping to what you want but then overriding it.

You should see that both keys map to the same string, because it's the final string in the second list.

You can achieve what you want using zip, there are examples here: Convert two lists into a dictionary

jtr
  • 11