Tuples (and namedtuples) as Python Dictionary Keys
Posted by Aly Sivji in Quick Hits
Was reading the Python design FAQs and saw that immutable elements can be used as dictionary keys.
Wait a minute.... tuples are immutable, can they be used as dictionary keys? YES!
my_dict = {}
my_dict[('Aly', 'Sivji')] = True
my_dict
What about namedtuples? YES! namedtuples are also immutable.
from collections import namedtuple
Person = namedtuple('Person', ['first_name', 'last_name'])
me = Person(first_name='Bob', last_name='Smith')
my_dict[me] = True
my_dict
Any immutable datatype can be used as a dictionary key!
My data structures can get even flatter!
import this
Stay Pythonic!
Updates¶
- 12/02/2017: Dictionary keys neeed to be hashable.
Comments