Home > database >  Loop Json ChainMap in Python
Loop Json ChainMap in Python

Time:12-03

I have the following python objects that contained the following values. I am only interested in the values inside "parameters".

injury=     {
    "class" :"Distribution",
    "dtype" :"str",
    "name" :"DiscreteDistribution",
    "parameters" :[
        {
            "No" :0.9794526467893897,
            "Yes" :0.02054735321061031
        }
    ],

}
rescued=        {
    "class" :"Distribution",
    "dtype" :"str",
    "name" :"DiscreteDistribution",
    "parameters" :[
        {
            "No" :0.9966289759244428,
            "Yes" :0.0033710240755573107
        }
    ],

}
manual_system_impact=       {
    "class" :"Distribution",
    "dtype" :"str",
    "name" :"DiscreteDistribution",
    "parameters" :[
        {
            "Made incident worse" :2.5685581140811714e-05,
            "Did not contain fire" :0.9752944628959785,
            "Extinguished fire" :0.020906757015599593,
            "Contained fire" :0.0037730945072812186
        }
    ],

}

I am using ChainMap to print only the values inside "parameters" of each of the objects.

I am using the following loop but I only get the values inside "parameters" of the first object (injury).

chained_dict = ChainMap(injury, rescued, manual_system_impact)

for i in chained_dict:
    if i == 'parameters':
        print(chained_dict['parameters'])

Can anyone help me to have a loop that prints the values inside "parameters" of each of the three objects, please? Any other method to obtain the "parameters" is welcome, it can also be in pandas.

CodePudding user response:

I feel like I didn't really get your question cause I don't undrstand why you don't simply use 3 prints... But maybe this help you

for d in [injury, rescued, manual_system_impact]:
    print(d['parameters'])

CodePudding user response:

You can do it even not creating a list (but creating silently a tuple in the end) :

for x in injury, rescued, manual_system_impact:
    print(x['parameters'])
  • Related