0

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'}
matszwecja
  • 6,357
  • 2
  • 10
  • 17
Ed Godalle
  • 13
  • 1
  • 1
    You need to somehow tell Python that it has to split into 3 different dicts. Right now you are creating a single dictionary, and because a dict can not contain duplicate keys, you are seeing only the last values. – matszwecja Jan 12 '23 at 09:26
  • 1
    Your approach for the conversion is correct, the question should be how to split a list into groups of 3 items. – VPfB Jan 12 '23 at 09:27

4 Answers4

1

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)]
tomerar
  • 805
  • 5
  • 10
0

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])
ashish singh
  • 6,526
  • 2
  • 15
  • 35
0

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'}]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

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)]
Stuart
  • 9,597
  • 1
  • 21
  • 30