Not sure if someone had that idea already.
It’s very simple:
dct = {"foo": 1, "bar": 2}
print(dct - {"foo"}) # prints {"bar": 2}
To achieve the equivalent currently, we could use a dict comprehension (I am using an inline set as the ‘excluded keys’ container intentionally in this example, even though it’s not the most optimal):
print({k: v for k, v in dct.items() if k not in {"foo"}})
Or a multiline solution (again, using inline set which compiles to a frozenset):
dct2 = dct.copy()
for key in {"foo"}:
del dct2[key]
print(dct2)
Everything else that comes to my mind is pretty much just a variant of one of above (rewriting the entire dict or removing some keys in-place on a copy).
I’m thinking this could be useful because -
is well recognized in context of set operations and dict, when being iterated over directly, is like an order-preserving set of keys—just like keys view that already supports -
… a quick note on keys view though, keys view supports -
but on any object supporting iter()
:
class FancyFilter:
def __getitem__(self, idx):
if idx == 0:
return "foo"
raise IndexError
print({"foo": 1, "bar": 2}.keys() - FancyFilter()) # {"bar": 2}
So if we blindly ‘copy-paste’ the implementation from dict keys view, we would allow this:
{"foo": 1, "bar": 2} - {"foo": 2}
Which is obviously super weird to read (and it’s not easy to guess whether the “difference” should as well apply to values, despite being theoretically often impossible because of unhashability), at least to me.
I think I’d use the set-like approach here that only allows sets in operators and any objects supporting iter()
in methods (I’m not suggesting we should add dict.difference
though).
I also thought of suggesting this to be applied to HAMT (HAMT is used for PEP 567 contexts, Python/hamt.c
) as well, but I think this is much less important than the suggestion for dict
which is essential in mapping storage in Python.