Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading