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

Replacing Value in Subelement of dictionary in Python

I got a dataset of entries with the IDs of gasoline stations and their current prices (diesel, e5 and e10). However, some of the gas stations are not selling every product and therefore the value for the field in the array is ‘false’

In detail the dict looks like this:

data = {
    "005056ba-7cb6-1ed2-bceb-662ba1a94d1f": {
        "status": "open",
        "e5": 1.839,
        "e10": 1.779,
        "diesel": 'false'
    },
    "005056ba-7cb6-1ed2-bceb-5332ab168d12": {
        "status": "open",
        "e5": 1.719,
        "e10": 'false',
        "diesel": 'false'
    },
    "00060723-0001-4444-8888-acdc00000001": {
        "status": "open",
        "e5": 1.839,
        "e10": 1.779,
        "diesel": 2.179
    }
}

To further process the response of the request I need to have all prices set to doubles, but since there are those ‘false’ values it wont accept it.

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

How can I replace all ‘false’ values to 0 to ensure that all the prices can be read as doubles?

>Solution :

Could you do something like this?

def sanitize_data(data):
    for key, value in data.items():
        for k, v in value.items():
            if v == "false":
                data[key][k] = 0.0

    return data

Example Result

{
    "00060723-0001-4444-8888-acdc00000001": {
        diesel: 2.179,
        e10: 1.779,
        e5: 1.839,
        status: "open"
    },
    "005056ba-7cb6-1ed2-bceb-5332ab168d12": {
        diesel: 0,
        e10: 0,
        e5: 1.719,
        status: "open"
    },
    "005056ba-7cb6-1ed2-bceb-662ba1a94d1f": {
        diesel: 0,
        e10: 1.779,
        e5: 1.839,
        status: "open"
    }
}
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