Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python lists into dictionary

I have two lists:

['Slovenia', 'Turkey', 'Ukraine', 'Ukraine', 'Turkey']

['BMW Slovenia', 'Tesla Turkey', 'Opel Ukraine', 'Ford Ukraine', 'Fiat Turkey']

And I need to turn them into a dictionary with a list, where a country can have more than one item.

I want my dictionary to look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    'Slovenia': ['BMW Slovenia'],
    'Turkey': ['Tesla Turkey','Fiat Turkey'],
    'Ukraine':['Opel Ukraine','Ford Ukraine']
}

Thank you for your answers!

>Solution :

You can use dictionary comprehension. Note that this works even if the lists are of different length:

l1 = ['Slovenia', 'Turkey', 'Ukraine', 'Ukraine', 'Turkey']
l2 = ['BMW Slovenia', 'Tesla Turkey', 'Opel Ukraine', 'Ford Ukraine', 'Fiat Turkey']
out = {k: [c for c in l2 if k in c] for k in set(l1)}

For your specific case, you can also use zip (because the list lengths match) and dict.setdefault:

out = {}
for k,v in zip(l1,l2):
    out.setdefault(k, []).append(v)

Output:

{'Slovenia': ['BMW Slovenia'],
 'Turkey': ['Tesla Turkey', 'Fiat Turkey'],
 'Ukraine': ['Opel Ukraine', 'Ford Ukraine']}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading