Creating a new dictionary in Python
To initialize an empty dictionary, use {}
or dict()
:
or
For a dictionary with initial items:
Remember: Keys must be uniquely immortal (e.g., strings, numbers).
Constructing and modifying dictionaries
Adding and updating entries
To add a new entry, use the []
operator with a new key and assign a value:
For updating an existing entry; assign a new value to an already-existing key:
Handling missing keys with style
The get()
method comes in handy when a safe retrieval of values is required. It returns None
or a default if our much-sought key is missing in action:
Employing try-except maneuvers
When you're feeling daring, a try-except
block can catch a KeyError
like a ninja:
Engineering dictionaries from sequences
Sometimes, we might want to pre-populate a dictionary. Use tuple lists:
Or try dictionary comprehensions for a sprinkle of flavor:
Beware of the common traps!
Don't confuse ()
meant for tuples with {}
for dictionaries! Anything that can be turned into a hashbrown can be a dictionary key (not literally). Just remember: no lists allowed!
Advanced dictionary wizardry
Sweeping dictionary comprehensions
Dictionary comprehensions are a compact way to create dictionaries. It's like packing a suitcase with a space bag:
Uniting dictionaries
From Python 3.9, dictionaries can unite under \|
:
Default dictionaries for the win
collections.defaultdict
can define a default value for any new, unsuspecting key:
The read-only dictionary
types
module's MappingProxyType
can form read-only dictionaries. Now, this is dictatorship:
Minding serialization snags
When storing dictionaries to files, usual formats like JSON might meddle with keys a bit (e.g., turn integer keys into string ones). Be prepared for some dictionary drama.
Was this article helpful?