intersection, union, difference, symmetric difference for dictionaries

Chris Angelico rosuav at
Sat Mar 1 23:29:25 CET 2014

On Wed, Feb 26, 2014 at 7:44 AM, John Gordon <gordon at> wrote:
> In <G57Pu.24239$Th2.4990 at> mauro <mauro at> writes:
>> - Dictionaries and sets are both accessed by key
> As far as I have used sets, they are not accessed by key.
>>>> x = set([1, 2, 'buckle my shoe'])
>>>> x
> set([1, 2, 'buckle my shoe'])
>>>> 1 in x
> True
>>>> 5 in x
> False

>>> x = {1:3, 2:4, 'buckle my shoe':'spamming the door'}
>>> x
{1: 3, 2: 4, 'buckle my shoe': 'spamming the door'}
>>> 1 in x
>>> 5 in x

A dict does the exact same thing with its keys as a set does with its
elements. Actually, one of the things that periodically trips me up
when I switch from Pike to Python is that a Python set can't be used
like this:

>>> x = set()
>>> x["test"] = 1
>>> x["foo"] = 1
>>> assert x == {"test","foo"}

Instead, I have to use x.add("test"). In Pike, I can treat a set as if
it were a mapping where every value is simply the integer 1 (Python
could use True instead). Setting it to any truthy value would add it,
setting to any falsy value would remove it. This wouldn't be a huge
change; it certainly wouldn't fundamentally change the set type -
because it *is* working with keys.

Hmm. Actually, it shouldn't be too hard to subclass and add that. Lessee.

class set(set):
    def __setitem__(self, key, state):
        if state: self.add(key)
        else: self.remove(key)
    def __getitem__(self, key):
        return key in self

I might need to toss that into or something. It'd work as long
as I don't use set literal notation anywhere.


More information about the Python-list mailing list