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