Search code examples
pythonjsondictionarydel

Unable to delete a dictionary key inside a json by using the del function. getting a TypeError


Code shorten for this example, I'm iterating through it as if it had multiple keys.

string = '''
{
    "people":
    {
        "a":
        {
            "parent":
            {
                "father": "x"
            }
        }
    }
}
'''

data = json.loads(string)

I make sure that my conditional is working, it outputs "ok", so it's fine.

for name in data["people"].values():
    if name["parent"]["father"] == "x":
        print("ok")

Then I modify the code above to delete that key and I get the following error:

TypeError: unhashable type: 'dict'

for name in data["people"].values():
    if name["parent"]["father"] == "x":
        del data["people"][name]

What am I doing wrong?

Thank you


Solution

  • You are trying to use name as a key, but name is actually a dictionary, not a string. Use .items() to get both the name and the contents:

    for name, contents in data["people"].items():
        if contents["parent"]["father"] == "x":
            del data["people"][name]
    

    However, note that this will not work either. You can't change the size of a dictionary while iterating it. You can force .items() to fully consume by calling list or similar on it:

    for name, contents in list(data["people"].items()):
        if contents["parent"]["father"] == "x":
            del data["people"][name]
    

    In the end, data will just be {'people': {}}, which I believe is what you want.