How to create a dictionary (also known as a hashmap) in Python
Published on Aug. 22, 2023, 12:15 p.m.
To create a dictionary (also known as a hashmap) in Python, you can use curly braces ({}) or the dict()
function. Here are some examples:
# Create a dictionary with curly braces
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict)
# Create a dictionary with the dict() function
my_dict = dict(key1='value1', key2='value2')
print(my_dict)
These will both output 'key1': 'value1', 'key2': 'value2'
, which is a dictionary with two key-value pairs.
You can also create an empty dictionary and add key-value pairs later:
# Create an empty dictionary
my_dict = {}
# Add a key-value pair
my_dict['key1'] = 'value1'
print(my_dict)
# Add another key-value pair
my_dict['key2'] = 'value2'
print(my_dict)
These will output 'key1': 'value1'
and 'key1': 'value1', 'key2': 'value2'
, respectively, as the key-value pairs are added.
Note that dictionary keys must be immutable (i.e. cannot be changed), so strings, numbers, and tuples are common choices for keys.