-2

I know that there are a bunch of ways to make a dictionary out of two lists, but I wanted to do it using two FOR loops to iterate over both lists. Therefore, I used the following code. Surprisingly, the code doesn't iterate over the second list that contains the values of the dictionary keys and only considers the last element of the list as the value.

key = ['hello', 'mello', 'vello']
value = [1, 2, 3]
dictionary = {k: v for k in key for v in value}
print('dictionary is ', dictionary)

the result was:

dictionary is: {'hello': 3, 'mello': 3, 'vello': 3}

But I expect that the result would be:

dictionary is: {'hello': 1, 'mello': 2, 'vello': 3}

I appreciate it if anyone can clarify this for me.

ajeddi1
  • 3
  • 1
  • "Surprisingly, the code doesn't iterate over the second list that contains the values of the dictionary keys" of course it does. Try doing justa regular nested loop and print out the values. It should be illuminating – juanpa.arrivillaga May 29 '21 at 07:47
  • 2
    It does iterate over the second list. overwritten. – TopW3 May 29 '21 at 07:48

2 Answers2

3

My understanding is the full dictionary is being recreated each loop with each number as the key, resulting in only your final output being that of the last value (best shown by reversing your key and value statements, returning {1: 'vello', 2: 'vello', 3: 'vello', 4: 'vello'}

If the other is your intended output, this should work fine:

dictionary = dict(zip(key,value))
Da1ne
  • 74
  • 3
0

You can use zip for this purpose.

dictionary = dict(zip(keys, values))
Robin De Schepper
  • 4,942
  • 4
  • 35
  • 56
TopW3
  • 1,477
  • 1
  • 8
  • 14
  • what do you want? Please make your question clear – TopW3 May 29 '21 at 07:47
  • I am asking this because somewhere else I wrote the following code, and it seems that it works properly. flowCost = {a: round(p, 0) for a in list(Graph.edges) for p in normPositiveList(normMean, normSig, len(list(Graph.edges)))} normPositiveList is a function that returns a list. I don't understand the logic behind it, although I know using zip() would solve the problem. – ajeddi1 May 29 '21 at 07:54