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

99
January 17, 2021, at 02:30 AM

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
Answer 1
a = ['A', 'B', 'C']
b = [ 1 ,  2 ,  3 ]
print (dict(zip(a,b)))

Output:

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

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}
Answer 3

You can also use enumerate

d = {elem: b[i] for i, elem in enumerate(a)}
d
{'A': 1, 'B': 2, 'C': 3}
READ ALSO
Android xml design slowing down my application

Android xml design slowing down my application

I have a layout design in my app

88
Passy password generator with boolean parameters

Passy password generator with boolean parameters

Wanted to know the best way to solve thisInput: Will be using the passayPassGenerator and setting the booleans

111
Dashboard Header button and footer button not getting aligned properly in concrete 5

Dashboard Header button and footer button not getting aligned properly in concrete 5

In concrete 5 - Under dashboard pages Header and footer buttons are not getting aligned properlyNeed help

191
Laravel 8 - Automatically update a form field when certain value is selected

Laravel 8 - Automatically update a form field when certain value is selected

I have a truck table and a postman tableBoth tables have a one to one relationship

97