Home > database >  How to combine 2 lists into a dictionary
How to combine 2 lists into a dictionary

Time:01-12

I have 2 lists below:

a = ['ymd', 'publisher_name', 'country_name', 'ymd', 'publisher_name', 'country_name', 'ymd', 'publisher_name', 'country_name']
b = ['2022-12-01',  'Media1', 'United Kingdom', '2022-12-01',  'Media1', 'Brazil','2022-12-01', 'Media1', 'Laos']

when I tried to use zip and dict the result is this:

zip(a,b)
dictList=dict(zip(a,b))
print (dictList)

#results (only the last list is printed)

{'ymd': '2022-12-01', 'publisher_name': 'Media1', 'country_name': 'Laos'}

#desired results

{'ymd': '2022-12-01', 'publisher_name': 'Media1', 'country_name': 'United Kingdom'},
{'ymd': '2022-12-01', 'publisher_name': 'Media1', 'country_name': 'Brazil'},
{'ymd': '2022-12-01', 'publisher_name': 'Media1', 'country_name': 'Laos'}

CodePudding user response:

you have almost got it but you need to pass pieces of length 3 into the function

def solve(a,b) :
    zip(a,b)
    dictList=dict(zip(a,b))
    print (dictList)
    
a = ['ymd', 'publisher_name', 'country_name', 'ymd', 'publisher_name', 'country_name', 'ymd', 'publisher_name', 'country_name']
b = ['2022-12-01',  'Media1', 'United Kingdom', '2022-12-01',  'Media1', 'Brazil','2022-12-01', 'Media1', 'Laos']

for i in range(0, len(a), 3):
    solve(a[i:i 3], b[i:i 3])

CodePudding user response:

It seems that you want multiple dictionaries so let's put them in a list as follows:

a = ['ymd', 'publisher_name', 'country_name', 'ymd', 'publisher_name', 'country_name', 'ymd', 'publisher_name', 'country_name']
b = ['2022-12-01',  'Media1', 'United Kingdom', '2022-12-01',  'Media1', 'Brazil','2022-12-01', 'Media1', 'Laos']

result = [dict()]

for k, v in zip(a, b):
    if len(result[-1]) == 3:
        result.append(dict())
    result[-1][k] = v


print(result)

Output:

[{'ymd': '2022-12-01', 'publisher_name': 'Media1', 'country_name': 'United Kingdom'}, {'ymd': '2022-12-01', 'publisher_name': 'Media1', 'country_name': 'Brazil'}, {'ymd': '2022-12-01', 'publisher_name': 'Media1', 'country_name': 'Laos'}]
  • Related