'Create dictionary from 3 lists - python
Looking for some help in creating a dictionary using 3 python lists
a = ['alpha','bravo','charlie']
b = ['a','b','c']
c = [1,2,3]
output:
{'alpha': {'letter': 'a', 'number': 1},
'bravo': {'letter': 'b', 'number': 2},
'charlie': {'letter': 'c', 'number': 3}}
I tried something like this. This may be close, but needs some tweaking:
{k: dict(v) for k,v in zip(a, zip(('letter', b),('number', c)))}
Solution 1:[1]
You should zip all 3 lists together:
result = {greek: {'letter': letter, 'number': number} for greek, letter, number in zip(a, b, c)}
Solution 2:[2]
A zip-heavy version (as you seem to have tried that):
output = {k: dict(zip(('letter', 'number'), vs))
for k, vs in zip(a, zip(b, c))}
Or:
output = {k: dict(zip(('letter', 'number'), vs))
for k, *vs in zip(a, b, c)}
Or to use your {k: dict(v) for k,v in zip(a, ...)} and only fix the ... part:
output = {k: dict(v) for k,v in zip(a, map(zip, repeat(('letter', 'number')), zip(b, c)))}
Or with some itertools, making C code do all the work (other than configuring the work):
from itertools import repeat
output = dict(zip(a, map(dict, map(zip, repeat(('letter', 'number')), zip(b, c)))))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
| Solution 2 |
