Home > Mobile >  Convert multiple lists with missing value into one dictionary
Convert multiple lists with missing value into one dictionary

Time:11-18

I am trying to add multiple lists into a dictionary - one key and one value list. I can do two lists to a dictionary but I am wondering how to do multiple lists joining with some missing value in one of the lists.

a = ['apple', 'orange', 'lemon']
b = ['London', 'New York', 'Tokyo']
c = ['Red', 'Orange', 'Yellow']
d = ['good', 'bad', '']

fruito = zip(a, b)
fruit_dictionary = dict(fruito); fruit_dictionary

Expected output:

fruit_dictionary = {'apple': ['London', 'Red', 'good'],
                    'orange': ['New York', 'Orange', 'bad'],
                    'lemon': ['Tokyo', 'Yellow']}

CodePudding user response:

You can use the following dictionary comprehension with zip and argument packing:

{k:v for k, *v in zip(a,b,c,d)}

output:

{'apple': ['London', 'Red', 'good'],
 'orange': ['New York', 'Orange', 'bad'],
 'lemon': ['Tokyo', 'Yellow', '']}

Or to get rid of empty strings:

{k:[e for e in v if e]      # using truthy values here, could also use e != ''
 for k, *v in zip(a,b,c,d)}

output:

{'apple': ['London', 'Red', 'good'],
 'orange': ['New York', 'Orange', 'bad'],
 'lemon': ['Tokyo', 'Yellow']}

lists of unequal lengths

For completeness, I am adding here a generic solution in case the input lists have different lengths. The solution would be to use itertools.zip_longest:

a = ['apple', 'orange', 'lemon']
b = ['London', 'New York', 'Tokyo']
c = ['Red', 'Orange', 'Yellow']
d = ['good', 'bad']

from itertools import zip_longest
{k:[e for e in v if e] for k, *v in zip_longest(a,b,c,d)}
  • Related