Reputation: 210
I am quite new to python so I tried to change a list of list to a dictionary by looping over it and defining a variblae that is a dictionary.
I have the result of a query as this:
a = [
[[1, 8, 2022], Decimal("666.6666666666666666666666667")],
[[8, 8, 2022], Decimal("10000")],
]
I would like to convert it to dictionary like this:
data_dict = {
'date': [1, 8, 2022],
'kpi' : 666.67
}
I tried this code:
cob = None
for x in a:
for b in x:
v = {"date": b[0], "kpi": b[1]}
cob = v
I got this error:
TypeError: 'decimal.Decimal' object is not subscriptable
how do I deal with this decimal How do I achieve this goal?
thank you for your time in advance.
Upvotes: 1
Views: 253
Reputation: 1180
cob = []
for b in a:
v = {"date": b[0], "kpi": float(b[1])}
cob.append(v)
Upvotes: -1
Reputation: 15
You can get the first index of every sublist in the larger list. Basically just use the zero index of each as the value.
d = {}
d["date"] = a[0][0]
d["kpi"] = a[1][0]
Upvotes: -1
Reputation: 36581
Something like the following will get it done. Within the list comprehension, only one level of iteration is taking place. Using float
will take care of converting the Decimal
.
[{'date': lst[0], 'kpi': float(lst[1])} for lst in a]
Yields:
[{'date': [1, 8, 2022], 'kpi': 666.6666666666666},
{'date': [8, 8, 2022], 'kpi': 10000.0}]
Upvotes: 3