Dictionary views "are set-like objects" and can thus be used to compare dictionary contents with other objects. Specifically,
- key-views: set-like
- value-views: not set-like
- item-views: set-like if (key, value) pairs are unique and hashable
The set-like nature of key-views allows bitwise comparisons. In Python 3, we can find the intersection using the &
operator.
hex_ids = {'#b0a7aa': '9976', '#595f5b': '19367', '#9a8f6a': '24095'}
hex_ids.keys()
# dict_keys(['#595f5b', '#9a8f6a', '#b0a7aa'])
{'#c7ccc0', '#9a8f6a', '#8a8e3e'} & hex_ids.keys()
# {'#9a8f6a'}
Oddly, comparing a list
and key-view is also possible:
['#c7ccc0', '#9a8f6a', '#8a8e3e'] & hex_ids.keys()
# {'#9a8f6a'}
whereas list
and set
objects normally cannot be compared this way.
['#c7ccc0', '#9a8f6a', '#8a8e3e'] & set(['#595f5b', '#9a8f6a', '#b0a7aa'])
# TypeError: unsupported operand type(s) for &: 'list' and 'set'
['#c7ccc0', '#9a8f6a', '#8a8e3e'] & {['#595f5b', '#9a8f6a', '#b0a7aa']}
# TypeError: unhashable type: 'list'
Aside from being set-like, why can key-views be compared to lists using bitwise operators?
Tested on: |Python 3.5.2|Python 3.4.4|Python 2.7.12 (using viewkeys()
)|IPython 5.0.0|