0

I got this question at an interview and I did not know how to solve it then and I am trying to solve it now.

If I have two lists:

l1 = [1, 3, 5, 7, 9]
l2 = [0, 2, 4, 8, 10]

how can I write a dict comprehension that will produce {1:0, 3:2, 5:4, 7:8, 9:10}?

Cristian M
  • 715
  • 2
  • 12
  • 32

2 Answers2

2
l1 = [1, 3, 5, 7, 9]
l2 = [0, 2, 4, 8, 10]
dict(zip(l1, l2))

output:

{1: 0, 3: 2, 5: 4, 7: 8, 9: 10}
Tal Folkman
  • 2,368
  • 1
  • 7
  • 21
0

You can use the zip built-in function to combine multiple lists into an iterable of tuples. This zip iterable can be made into a dictionary.

Syntax

for (valueoflist1,valueoflist2) in zip(list1,list2):
   #Code

Code resolution:

result = {key: val for key ,val in zip(keys ,values)}

or

    result = dict(zip(keys, values))
Simon Crowe
  • 301
  • 3
  • 14
XxJames07-
  • 1,833
  • 1
  • 4
  • 17