简体   繁体   中英

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

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

You should zip all 3 lists together:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM