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!
CodePudding user response:
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']}
CodePudding user response:
Use zip
to pair the two lists, and a collections.defaultdict
to store the results
from collections import defaultdict
x = ['Slovenia', 'Turkey', 'Ukraine', 'Ukraine', 'Turkey']
y = ['BMW Slovenia', 'Tesla Turkey', 'Opel Ukraine', 'Ford Ukraine', 'Fiat Turkey']
result = defaultdict(list)
for key, val in zip(x, y):
result[key].append(val)
print(result)
# {'Slovenia': ['BMW Slovenia'],
# 'Turkey': ['Tesla Turkey', 'Fiat Turkey'],
# 'Ukraine': ['Opel Ukraine', 'Ford Ukraine']}