#9
Inspired Python
>>> d = {"first_name": "Cosmo", "last_name": "Kramer"}
>>> keys = d.keys()
# dict_keys inherits from the Set abstract base class
>>> isinstance(keys, collections.abc.Set)
True
# Check that the set containing "first_name" is a subset of keys
>>> {"first_name"} < keys
True
# Unions also work
>>> {"age"} | keys
{'age', 'first_name', 'last_name'}
# As do intersections
>>> {"last_name", "address", "website"} & keys
{'last_name'}

Python Dictionary Tricks: Keys are set-like and support most set operations


Because keys must be hashable and unique in a dictionary, they act like sets. You can use most set-like operations on them, and because they’re views, they always reflect the actual contents of the underlying dictionary. But because it’s a view it is read-only. Values, however, are not set-like; they can contain complex unhashable objects and may contain duplicates.

Be Inspired Get Python tips sent to your inbox

We'll tell you about the latest courses and articles.

Absolutely no spam. We promise!