Skip to content
Advertisement

How can I replace a string value with its corresponding Boolean value in a nested dictionary in Python?

I was recently given a project to do for my Python college course. Basically, you save a dictionary in a csv file with csv.DictWriter, and then you load it back into another dictionary with csv.DictReader. However, for some reason, one of the automated unittests fails my function because the final dictionary contains values “True” or “False” instead of Bool values True or False (which I just consider to be logical, given we literally read a string from a file and placed it into a dictionary).

Anyways, I’ve been toying around with the idea of actually replacing these before my function returns the dict, but even the version of the code that somehow works in terms of syntax is not functional logically, and the True and False values remain strings. Here’s an example of what I tried:

a = {
    "b": {
        "name": "gari",
        "last_name": "jovan",
        "truth": "True"
    },

    "c": {
        "name": "miki",
        "last_name": "milane",
        "truth": "False"
    },

    "d": {
        "name": "baki",
        "last_name": "mico",
        "truth": "True"
    }
}

for i in a: #we approach individual small dicts
    for j in i: #we approach keys in said dicts
        if j == "truth":
            if j["truth"] == "False":
                j["truth"] == False
            elif j["truth"] == "True":
                j["truth"] == True
            else:
                raise Exception("Greska")
        else:
            pass
    else:
        pass

print(a)

As I said, this is just a contained example, not something from my actual project, because I tried figuring the actual solution through an isolated piece of code. Still, this doesn’t seem to work, and I was just wondering if anyone would be able to help me out.

Thanks in advance!

Advertisement

Answer

Try:

a = {
    "b": {"name": "gari", "last_name": "jovan", "truth": "True"},
    "c": {"name": "miki", "last_name": "milane", "truth": "False"},
    "d": {"name": "baki", "last_name": "mico", "truth": "True"},
}


for d in a.values():
    d["truth"] = d["truth"] == "True"

print(a)

Prints:

{
    "b": {"name": "gari", "last_name": "jovan", "truth": True},
    "c": {"name": "miki", "last_name": "milane", "truth": False},
    "d": {"name": "baki", "last_name": "mico", "truth": True},
}

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement