How to combine 2 lists into a dictionary

Question:

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'}
Asked By: Ed Godalle

||

Answers:

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])
Answered By: ashish singh

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'}]
Answered By: Fred

you can use this example it will going to work and combine 2 lists into a dictionary

final_list = [{a:b for a,b in zip(a[i:i+3], b[i:i+3])} for i in range(0, len(a), 3)]
Answered By: tomerar

Adapt this recipe to divide the zipped lists into chunks, then turn that into a list of dicts.

result = [dict(chunk) for chunk in zip(*[zip(a, b)] * 3)]
Answered By: Stuart
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.