Can we have a .delete() for dictionary please

I would like to see a .delete() that doesn’t raise KeyError if the key doesn’t exist.
I’m suggesting .delete() so that existing code is not affected.

I’m dealing with json input from Grinding Gear Games and i’m getting really sick of this:

    if gem.get("baseTypeName"):
        del gem["baseTypeName"]
    if gem["grantedEffect"].get("baseTypeName"):
        del gem["grantedEffect"]["baseTypeName"]
    if gem["secondaryGrantedEffect"].get("baseTypeName"):
        del gem["secondaryGrantedEffect"]["baseTypeName"]

The dictionary is from a json.load()
If the key doesn’t exist, and I’m trying to delete it - why should Python care ??? I certainly don’t.

It may not have much use case from point of view but those of us who can create cleaner code with it, will make a big deal out of it.

I think it is an easy add-on for you (most of the code is already there) and it would be good it you could add it into the next patch python 3.11.8 or 3.11.9 if it’s coming.

I say 3.11 as 3.12 doesn’t work on my application which is still developing and I’m not interested in debugging for 3.12 yet.

thanks very much
hoping you take this seriously
Peter

PS: why can’t I add dictionary and delete as tags ???

You can use pop with a default value if you don’t care about errors when deleting a key.

3 Likes

You can use the dict.pop method and provide a default argument to avoid the key error.

gem.pop("baseTypeName", None)
gem.get("grantedEffect", {}).pop("baseTypeName", None)
gem.get("secondaryGrantedEffect", {}).pop("baseTypeName", None)
2 Likes

I was reading pop, but didn’t see it had a default. Never thought it should have.

Ok. We can close this.

ty

Could you mark one of our answers as the Solution? :smile:

Btw discard would be a better name, as that’s what it’s called for sets.

1 Like

Just for future reference, features don’t get added to patch releases, that’s just not how software development lifecycles work. The earliest something new could be added to Python is 3.13, and even that would be pushing it for most things that haven’t already been decided on.

Another trick you can use for bulk removals is to filter them out:

def without(a_dict, keys):
    return {k:v for k, v in a_dict.items() if k not in keys}
3 Likes

Happy too. How. I’m hovering over everything. There’s no obvious “mark this as the answer” button.
Yours is a good solution for the my exact issue.

with Karl’s expanding it, for when it gets above half a dozen entries :slight_smile:

Thanks

Good solution for the issue.
many thanks. I love list comprehension