Reputation: 13
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'}
Upvotes: 0
Views: 122
Reputation: 9858
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)]
Upvotes: 0
Reputation: 860
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)]
Upvotes: 1
Reputation: 26998
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'}]
Upvotes: 0
Reputation: 6904
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])
Upvotes: 0