Explain Codes LogoExplain Codes Logo

Creating a new dictionary in Python

python
dictionaries
comprehensions
defaultdict
Anton ShumikhinbyAnton Shumikhin·Aug 3, 2024
TLDR

To initialize an empty dictionary, use {} or dict():

new_dict = {}

or

new_dict = dict()

For a dictionary with initial items:

new_dict = {'apple': 2, 'banana': 3}

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:

my_dict = {} my_dict['new_key'] = 'new_value' # Create a key called 'new_key' and its best friend 'new_value'

For updating an existing entry; assign a new value to an already-existing key:

my_dict['new_key'] = 'updated_value' # 'new_key' got an upgrade!

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:

value = my_dict.get('missing_key', 'default_value')

Employing try-except maneuvers

When you're feeling daring, a try-except block can catch a KeyError like a ninja:

try: value = my_dict['uncertain_key'] except KeyError: value = 'default_value' # Plan B activated!

Engineering dictionaries from sequences

Sometimes, we might want to pre-populate a dictionary. Use tuple lists:

dict_from_tuples = dict([('key1', 1), ('key2', 2), ('key3', 3)])

Or try dictionary comprehensions for a sprinkle of flavor:

dict_comp = {k: v for k, v in [('key1', 1), ('key2', 2), ('key3', 3)]}

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:

squared_dict = {x: x**2 for x in range(6)} # Squares make the rules here

Uniting dictionaries

From Python 3.9, dictionaries can unite under \|:

combined = dict1 | dict2 # dict2 values overthrow overlapping dict1 values

Default dictionaries for the win

collections.defaultdict can define a default value for any new, unsuspecting key:

from collections import defaultdict default_dict = defaultdict(int) # all new keys will have a default value of 0 default_dict['new_key'] += 1

The read-only dictionary

types module's MappingProxyType can form read-only dictionaries. Now, this is dictatorship:

from types import MappingProxyType read_only = MappingProxyType(existing_dict)

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.