Jsh0s
Jsh0s

Reputation: 599

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

Upvotes: 1

Views: 53

Answers (2)

slacklikehellking9
slacklikehellking9

Reputation: 23

Try this:

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

data = json.loads(string)
l = []

for key, values in data["people"].items():
    if values["parent"]["father"] == "x":
        l.append(key)

for x in l:
    data["people"].pop(x)

print(data)

Upvotes: 1

iz_
iz_

Reputation: 16613

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.

Upvotes: 1

Related Questions