Home > OS >  Trying to iterate over lists and nested list to zip items into dictionary
Trying to iterate over lists and nested list to zip items into dictionary

Time:04-18

I have two lists, one of them contains a view hundred nested lists. I want to combine items of both and zip them into a dict.

code example:

list1 = ['SYNNR', 'NAME', 'BUNDESLAND']
list2 = [['11032', 'POYSDORF-OST', 'NOE'], ['11033', 'POYSDORF-WEST', 'NOE'], ['11034', 'POYSDORF-NORD', 'NOE']]

#iterate and zip
for i in range(len(list2)):
    result = dict(zip(list1, list2[i]))
print(result)

result

{'SYNNR': '11034', 'NAME': 'POYSDORF-NORD', 'BUNDESLAND': 'NOE'}

Only the last list inside list2 gets zipped in the dict. but I need to get dict for every list inside list2, like this

{'SYNNR': '11032', 'NAME': 'POYSDORF-OST', 'BUNDESLAND': 'NOE'}, {'SYNNR': '11033', 'NAME': 'POYSDORF-WEST', 'BUNDESLAND': 'NOE'}, {'SYNNR': '11034', 'NAME': 'POYSDORF-NORD', 'BUNDESLAND': 'NOE'}

Thanks for ideas!!

CodePudding user response:

Your code only returns the last dict that you create. Perhaps, instead of a single dict, you wanted a list of dicts:

result = []
for i in range(len(list2)):
    result.append(dict(zip(list1, list2[i])))
print(result)

However, as usual, instead of using the range(len(... idiom you can express this directly as a list comprehension:

result = [dict(zip(list1, line)) for line in list2]

CodePudding user response:

The problem is that you are overwriting the result variable for every item in the list, instead, you should have an array of dictionaries for the result variable

#iterate and zip
result = []
for i in range(len(list2)):
    result.append(dict(zip(list1, list2[i])))
print(result)

Another, optional improvement you could do is to simplify the first for, that would improve readability

result = []
for item in list2:
    result.append(dict(zip(list1, item)))
print(result)
  • Related