Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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},
    },
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading