Add Difference Operators To Dict

Oops I really should’ve read through the thread before responding to the post above right away. I now see why you believed that one should iterate over the dict instead of the iterable.

Instead of copying everything in the dict on the left and then iterating over the iterable on the right to delete keys from the dict copy, which incurs a lot of memory overhead, I think it would cost a lot less to create a a temporary set from the iterable with only items that are in the dict so to perform dict - set in the usual way:

def dict_exclude(d, iterable):
    to_exclude = set(filter(d.__contains__, iterable))
    return {k: v for k, v in d.items() if k not in to_exclude}
1 Like