I am trying to get arbitrary values from nested dictionaries, but getting an error.
My approach works for one level dict
like this:
table = [
{
"A": 157,
"B": 221,
"C": 330,
"D": 380
},
{
"A": 510,
"B": 547,
"C": 660,
"D": 780
},
{
"A": 791,
"B": 1111,
"C": 1200,
"D": 3000
},
]
from operator import itemgetter
val = 525
for dv in table:
column_B = max(val, dv['B'])
if val <= dv['B']:
column_A = (dv['A'])
column_C = dv['C']
pct = dv['D']
break
But if I nest the dicts, I get an error.
table = [
"inner":{
{ "A": 157,
"B": 221,
"C": 330,
"D": 380
},
{
"A": 510,
"B": 547,
"C": 660,
"D": 780
},
{
"A": 791,
"B": 1111,
"C": 1200,
"D": 3000
},
}
]
I get an error with above nested dict. I tried slicing, even tried reduced function but could not make it work up this point. What am I getting wrong here?
[]
denotes a list. {}
denotes a dictionary. It looks like you've gotten the two partially mixed up. In order for table
to make sense, table
should be a dictionary, and "inner"
should be a list.
# This has a key, therefore it's a dict.
table = {
# This has no keys, so it's a list.
"inner": [
{ "A": 157,
"B": 221,
"C": 330,
"D": 380
},
{
"A": 510,
"B": 547,
"C": 660,
"D": 780
},
{
"A": 791,
"B": 1111,
"C": 1200,
"D": 3000
},
]
}