Remove Key from Immutable Dict in Python
Here's a way to remove an attribute by key from an immutable dict in Python.
Mutable Delete
The usual answer is to just delete the attribute:
>>> obj = { "a": 1, "b": 2 }
>>> del obj["a"]
>>> obj
{'b': 2}
But that modifies the obj
dict. Modifications to shared state allow for a class of bugs that we can avoid.
Mutable Delete Copy
We want to avoid modifying the original dict, and we can make a copy and delete the key from it:
>>> obj2 = { "a": 1, "b": 2 }
>>> obj3 = {**obj2}
>>> del obj3["a"]
>>> obj3
{'b': 2}
>>> obj2
{'a': 1, 'b': 2}
This is better. It doesn't modify the original. But it takes multiple operations, and it's easy to forget to copy.
Immutable List Comprehension
What we really want is essentially a filter. We could use the filter
api, but in Python it's more idiomatic to do a list comprehension:
>>> obj4 = {x: obj2[x] for x in obj2 if x not in {"a"}}
>>> obj4
{'b': 2}
>>> obj2
{'a': 1, 'b': 2}
This is nice because it's immutable. And it's somewhat fluent. But it is an expression that contains many symbols that are somewhat difficult to visually parse.
Omit Helper
It's unfortunate that there isn't a convenience function for this in the stdlib. It seems a common-enough use case.
If you have a place for a little utility function, it might look like:
def omit(d, keys):
return {x: d[x] for x in d if x not in keys}
Called like:
omit(obj4, {"a"})
Do you have a more fluent method of doing the same thing?