1

I have two lists, for example:

A = [1, 2, 3, 4 ,5]

and

B = [23, 34, 44, 43, 32]

I have initialized an empty dictionary

D = {}

I want to pick an element from A as key and pick the corresponding element from B as value. For example the dictionary should look like:

D = {1: 23, 2: 34, 3: 44, 4:43, 5:32}

So far, I have done the following:

D = {}
for k in A:
   for j in B:
       D[k] = j
print("D is", D)

This only gives me an output as follows:

D = {1: 32, 2: 32, 3: 32, 4:32, 5:32}

For some reason, it only pulls the last value from B which is not desirable. Please help.

  • "For some reason" -> The reason is because for every one value `k`, you run `D[k] = j` `len(B)` times. Of those times, only the last one matters, since each prior assignment will be overwritten by the next – Alexander Mar 03 '21 at 02:36
  • Makes sense! Thanks for mentioning! – Sayanta Seth Mar 03 '21 at 22:06

1 Answers1

2

@ShadowRanger's solution

d = dict(zip(A, B))

For the second question, assuming you have a list A with length m. The for loop will run m * m times. In the last m running, it will assign 32 which is the last element in the B to every key in D.

Blaise Wang
  • 556
  • 5
  • 17