Is it possible to use two (non-nested) for loops inside a dicitonary?

Viewed 112

I have these two lists:

a = ['A', 'B', 'C']
b = [ 1 ,  2 ,  3 ]

And I want to merge them into a dictionary like this:

{'A': 1, 'B': 2, 'C': 3}

I already tried doing stuff like:

{i: j for i in a for j in b}
dict(*a: *b)

Which outputs

{'A': 3, 'B': 3, 'C': 3}
SyntaxError: invalid syntax
3 Answers
a = ['A', 'B', 'C']
b = [ 1 ,  2 ,  3 ]

print (dict(zip(a,b)))

Output:

{'A': 1, 'B': 2, 'C': 3}

You should better use zip for this:

a = ['A', 'B', 'C']
b = [ 1 ,  2 ,  3 ]

{i:k for i,k in zip(a,b)}

#{'A': 1, 'B': 2, 'C': 3}

You can also use enumerate

d = {elem: b[i] for i, elem in enumerate(a)}
d

{'A': 1, 'B': 2, 'C': 3}
Related