Home > Back-end >  Create dictionary from different lists correlated
Create dictionary from different lists correlated

Time:11-14

I want create a dictionary from multiple lists

list_countries=['italy','france']
list_leagues=[['serie-a','serie-b'], 'ligue-1']

keys=['Country','League']
values=[list_countries,list_leagues]

spam = [dict(zip(keys, item)) for item in zip(*values)]
print(spam)

Output

[{'Country': 'italy', 'League': ['serie-a', 'serie-b']}, 
{'Country': 'france', 'League': 'ligue-1'}]

Expected output

[{'Country': 'italy', 'League': 'serie-a'}, 
{'Country': 'italy','League': 'serie-b'}, 
{'Country': 'france', 'League': 'ligue-1'}]

CodePudding user response:

something like this

list_countries=['italy','france']
list_leagues=[['serie-a','serie-b'], 'ligue-1']
data = []
for c,l in zip(list_countries,list_leagues):
  if isinstance(l,list):
    for ll in l:
      data.append({'Country':c,'League':ll})
  else:
      data.append({'Country':c,'League':l})

print(data)

output

[{'Country': 'italy', 'League': 'serie-a'}, {'Country': 'italy', 'League': 'serie-b'}, {'Country': 'france', 'League': 'ligue-1'}]

CodePudding user response:

If you want to use a list comprehension:

spam = [dict(zip(keys, [a,c])) for a,b in zip(*values)
         for c in (b if isinstance(b,list) else [b])]

Output:

[{'Country': 'italy', 'League': 'serie-a'},
 {'Country': 'italy', 'League': 'serie-b'},
 {'Country': 'france', 'League': 'ligue-1'}]
  • Related