Things You Didn’t Know About Python Dictionaries
Valid keys, multiple ways to create, default values, view objects
The dictionary is one of the language’s most powerful data types. In other programming languages and computer science in general, dictionaries are also known as associative arrays. They allow you to associate one or more keys to values.
In this article, I’ll share some beyond the basics tips and tricks about dictionaries.
Valid dictionary keys
You can put anything in a dictionary. You’re not limited to numbers or strings. In fact, you can put dictionaries and Python lists inside your dictionary and access the nested values in a very natural way.
If you want, you can go pretty crazy on your dictionary keys too. The only requirement is that the key is hashable. Mutable types like lists, dictionaries, and sets won’t work and result in an error like: TypeError: unhashable type: ‘dict’
.
Besides this limitation, you can use all data types as a dictionary key, including native types like float
and int
or even a class name or object. Although completely useless for most, I'll demonstrate anyway:
>>> crazy_dictionary = { int: 1, float: 2, dict: 3 }
>>> crazy_dictionary[dict]
3
>>> class P:
…