Python nested dictionary value convert to float or decimal from string

I have following dictionary

data={"Volkswagen":{
          "Caddy Kombi":{
             "2022":"285000000.00",
             "2021":"212500000.00"
          },
          "Caddy Cargo":{
             "2022":"193100000.00",
             "2021":"190100000.00",
             "2019":"1289456545.00"
          }
       },
     "Tesla":{
          "Model 3":{
             "2022":"707160000.00",
             "2021":"630000000.00",
             "2020":"630000000.00"
          },
          "Model S":{
             "2021":"630000000.00",
             "2020":"630000000.00"
          },
          "Model X":{
             "2021":"1102500000.00",
          },
          "Model Y":{
             "2021":"735000000.00",
             "2020":"735000000.00"
          }
       }}

I want to convert all the string prices to float values i.e "2021":285000000.00
I tried upto here but result is not expectd At the end I want same dictionary being converted to float

for i, y in data.items():
         for k, x in y.items():
            for z,q in (y[k].items()):
               print(float(q))
               dictionary = {
                  i: {
                     k: x
                  }
               }
               print(dictionary)

>Solution :

You can try recursion:

def to_float(o):
    if isinstance(o, dict):
        for k, v in o.items():
            if isinstance(v, str):
                o[k] = float(v)
            else:
                to_float(v)
    elif isinstance(o, list):
        for v in o:
            to_float(v)


to_float(data)
print(data)

Prints:

{
    "Volkswagen": {
        "Caddy Kombi": {"2022": 285000000.0, "2021": 212500000.0},
        "Caddy Cargo": {
            "2022": 193100000.0,
            "2021": 190100000.0,
            "2019": 1289456545.0,
        },
    },
    "Tesla": {
        "Model 3": {
            "2022": 707160000.0,
            "2021": 630000000.0,
            "2020": 630000000.0,
        },
        "Model S": {"2021": 630000000.0, "2020": 630000000.0},
        "Model X": {"2021": 1102500000.0},
        "Model Y": {"2021": 735000000.0, "2020": 735000000.0},
    },
}

Leave a Reply