Home > Software engineering >  Create dictionary from 3 lists - python
Create dictionary from 3 lists - python

Time:05-24

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)))}

CodePudding user response:

The dict comprehension can zip all three iterables at once, and just include a dict literal for the sub-dict:

{k: {'letter': let, 'number': num} for k, let, num in zip(a, b, c)}

CodePudding user response:

You should zip all 3 lists together:

result = {greek: {'letter': letter, 'number': number} for greek, letter, number in zip(a, b, c)}

CodePudding user response:

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)))))
  • Related