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}}
CodePudding user response:
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)
CodePudding user response:
x = [['710.09', '65.09', '2.0'], ['710.09', '65.09', '3.0']]
y = ['rent', 'size', 'rooms']
{i: dict(zip(y, list(
map(float,j)
)
)) for i, j in enumerate(x, 1)}
zip: It will create a list dict between your keys 'rent', 'size' etc with values given in x
map: It will convert the values of x inside list to floats, finally
enumerate: will start the final dictionary with keys start from 1
Combining all of this inside dictionary comprehension to make a final dictionary.
Output:
{1: {'rent': 710.09, 'size': 65.09, 'rooms': 2.0},
2: {'rent': 710.09, 'size': 65.09, 'rooms': 3.0}}