What happens when you set a dictionary in python?

Viewed 245

I was trying out some ideas to solve an unrelated problem when I came across this behavior when using set on a dictionary:

a = {"a": 1}

b = {"b": 2}

c = {"a": 1}

set([a, b, c])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-7c1da7b47bae> in <module>
----> 1 set([a, b, c])

TypeError: unhashable type: 'dict'

d = {"a": 1, "b": 2}

set(d)
Out[23]: {'a', 'b'}

set(a)
Out[24]: {'a'}

I kind of understand why the set of dictionaries is unhashable (they're mutable), but the whole thing does not make that much sense to me. Why is set(a) and set(d) returning just the keys and how would that be useful?

Thank you!

2 Answers

The function set(x) takes any iterable x and puts all the iterated values into a set.

Dictionaries are iterable. When you iterate through a dictionary, you are given the keys. So set(d) will give you a new set containing all the keys of the dict d.

set converts an arbitrary iterable to a set, which means getting an iterator for its argument. The iterator for a dict returns its keys. It's not so much about set being useful with a dict, but set not caring what its argument is.

As for why a dict iterator returns the keys of the dict, it's a somewhat arbitrary choice made by the language designer, but keep in mind that given the choice of iterating over the keys, the values, or the key-value pairs, iterating over the keys is probably the best compromise between usefulness and simplicity. (All three are available explicitly via d.keys(), d.values(), and d.items(); in some sense iter(d) is a convenience for the common use case of d.keys().)

Related