Add nested list elements to nested dictionary

I’m looking for a way to add the nested list elements to a dictionary. My current approach only adds the last list element to the dictionary. Any help would be very much appreciated!

list = [['710.09', '65.09', '2.0'], ['710.09', '65.09', '3.0']]
categories =  {'rent': None, 'size': None, 'rooms': None}

for element in list:
   list=dict(zip(categories, element))
output: {'rent': 710.09, 'size': 65.09, 'rooms': 3.0}

desired output: {1:{'rent': 710.09, 'size': 65.09, 'rooms': 2.0},2:{'rent': 710.09, 'size': 65.09, 'rooms': 3.0}}

>Solution :

list = [['710.09', '65.09', '2.0'], ['710.09', '65.09', '3.0']]
categories = {'rent': None, 'size': None, 'rooms': None}
d = {index + 1: dict(zip(categories, item)) for index, item in enumerate(list)}
print(d)

Output:

{1: {'rent': '710.09', 'size': '65.09', 'rooms': '2.0'}, 2: {'rent': '710.09', 'size': '65.09', 'rooms': '3.0'}}

Or a little less golfy:

list = [['710.09', '65.09', '2.0'], ['710.09', '65.09', '3.0']]
categories = {'rent': None, 'size': None, 'rooms': None}
totals = dict()
for index, item in enumerate(list):
    totals.update({
        index + 1: dict(zip(categories, item))
    })

print(totals)

Leave a Reply