Add a dictionary to a `set()` with union

No that's impossible by definition. The way hash tables (like dicts and sets) do lookups is fundamentally unique from the way arrays (like lists) do lookups. The logical error is that if you have a datatype that only saves duplicates, what happens if you mutate one of the elements to be non-unique?

a, b = [0], [0, 1]
s = SpecialSet(a, b)
a.append(1)  # NOW WHAT?!

If you want to add a dictionary to a set, you can add the dict.items view of it (which is really just a list of tuples), but you have to cast to tuple first.

a = {1:2, 3:4}
s = set()
s.add(tuple(a.items()))

Then you'd have to re-cast to dict that once it leaves the set to get a dictionary back

for tup in s:
    new_a = dict(tup)

A built-in frozendict type was proposed in PEP416 but ultimately rejected.


Using set.union(), ask for the elements of the argument to the method to be added to the set, not the object itself. Iterating over a dictionary gives you the keys. You'd get similar results if you used set.union() on a list, a tuple or a string, the contents of those are added to the set:

>>> s = {42}
>>> s.union('foo')
set([42, 'o', 'f'])

The single-character strings 'o' and 'f' were added, not the string 'foo'.

You cannot add dictionaries to a set, because they are mutable; sets only support storing hashable objects, and one of the requirements for an object to be hashable, is that they are immutable.