3

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']}

1 Answer 1

9

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)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.