Introduction
A Python dictionary is a data structure that stores key-value pairs. Unlike lists, which use integer indices to access values, dictionaries use keys that can assume other types, such as strings. This makes dictionaries a powerful tool for organizing and retrieving data efficiently.
Dictionaries are implemented using hash tables, which provide a method for fast access to values based on associated keys.
Dictionary Literals
A dictionary literal is defined using curly braces {} and consists of comma-separated key-value pairs, where each key is separated from its value with a colon.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"}
In this example, my_dict contains three key-value pairs, where “name”, “age”, and “city” are keys, and “Saurus”, 30, and “New York” are their corresponding values.
Creating Empty Dictionaries
You can create an empty dictionary by using empty curly braces {}.
Example:
empty_dict = {}
The Python Dictionary Constructor
Dictionaries can also be created using the dict() constructor function by passing key-value pairs as keyword arguments. Each pair is specified as key=value.
Example:
my_dict = dict(name="Saurus", age=30, city="New York")
The constructor will consider the parameter names as string keys and produce the same result as the first dictionary literal example.
The dict() constructor will also create a dictionary out of any iterable, whose items are two-value iterable objects. This iterable is typically given as a list of tuples.
Example:
my_dict = dict([("name", "Saurus"), ("age", 30), ("city", "New York")])
In this example, dict() is given a list of tuples. The first item in each tuple is taken as the key and the second the value.
The following is a more unusual example of creating a dictionary.
Example:
my_dict = dict(["ab", "cd", "ef"]) print(my_dict)
Output:
{'a': 'b', 'c': 'd', 'e': 'f'}
This works because Python strings are also iterables on the individual characters they contain.
Accessing Dictionary Values
You can access the values in a dictionary by specifying the key inside square brackets [] or using the get() method.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} # Using square brackets name = my_dict["name"] print(name) # Using the get() method age = my_dict.get("age") print(age)
Output:
Saurus 30
Both approaches will retrieve the values associated with the specified keys, resulting in name
containing "Saurus"
and age
containing 30
.
However, there is one important difference between the square brackets and get() way of accessing a dictionary.
The square brackets will generate an error (KeyError
) if the key is not in the dictionary.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} my_dict["height"]
Output:
... KeyError: 'height'
The get() method will work fine with a non-existing key and return a None
value be default.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} print(my_dict.get("height"))
Output:
None
The default value for get()
can be changed by passing it as a second argument.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} print(my_dict.get("height", "Not in Dictionary"))
Output:
Not in Dictionary
Immutability of Python Dictionary Keys
Dictionary keys have to be immutable objects, namely objects whose internal state cannot change after they are defined. Lists and dictionaries are not immutable because they can be modified and therefore cannot serve as keys.
Example:
{[1, 2]: 3}
Output:
TypeError: unhashable type: 'list'
This example produces an error because [1, 2]
is a list and therefore can’t be a key, since lists are mutable. The error produced is TypeError: unhashable type: <SOME TYPE>. When you encounter this error in the context of a dictionary, you’ll know it’s because you used a mutable key.
If you need ordered items as keys, tuples are a great choice.
Example:
{(40.7128, "N", 74.0060, "W"): "New York", (34.0549, "N", 118.2426, "W"): "Los Angeles"}
The dictionary in the example above relates global coordinate keys to cities. It uses tuple keys and therefore does not generate an error.
Python dictionary keys must be immutable because it’s ambiguous what should happen when a key changes. Should accessing the value using the old version of the key still work or not? Python avoids this problem by requiring immutability.
Dictionary Operations
Modifying Dictionary Values
To change the value associated with a specific key, you can use square brackets to access the key and then assign a new value to it.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} my_dict["age"] = 31 print(my_dict)
Output
{'name': 'Saurus', 'age': 31, 'city': 'New York'}
In the example above, the age is changed from 30 to 31.
Adding an Item to a Dictionary
You can add new key-value pairs to a dictionary by specifying the new key and its associated value using square brackets.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} my_dict["job"] = "Engineer" print(my_dict)
Output:
{'name': 'Saurus', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
The my_dict
dictionary now includes a new key “job” with the value “Engineer”.
Popping an Item From a Dictionary
A pop operation for a dictionary removes a key-value pair and returns the value. It can be done using the dictionary pop() method, which is given the key to be removed as an argument.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} age = my_dict.pop("age") print(f"Age: {age}") print(my_dict)
Output:
Age: 30 {'name': 'Saurus', 'city': 'New York'}
In the example above, pop()
removes the key-value pair with the key “age” from the dictionary and returns the associated value, 30.
If the key given to pop()
is not in the dictionary, a KeyError
error is generated.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} my_dict.pop("height")
Output:
... KeyError: 'height'
The error can be avoided by giving pop()
a default value. The default is given as the second, optional argument to pop()
. When it’s given, pop()
returns it if the key is not in the dictionary. Otherwise, pop()
returns the value associated with the key, as it normally does.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} height_in_meters = my_dict.pop("height", 1.85) print(height_in_meters)
Output:
1.85
This example adds the default height of 1.85 (meters) to the call to pop()
. Since
“height” is not in the dictionary, the call returns the given default value, 1.85, and no error is generated.
Deleting an Item From a Dictionary
You can delete a key-value pair from a dictionary using the del
statement, specifying the item to delete with the same square bracket notation as for dictionary access.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} del my_dict["age"] print(my_dict)
Output:
{'name': 'Saurus', 'city': 'New York'}
After executing the del
statement, the “age” key and its associated value are removed from my_dict
.
As with pop()
, if the key is not in the dictionary, a KeyError
error is generated. However, there are no defaults with del
.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} del my_dict["height"]
Output:
... KeyError: 'height'
Checking if a Key Exists
You can check if a specific key exists in a dictionary using the in
keyword. It returns True
if the key exists and False
if it does not.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} if "age" in my_dict: print("Age exists in the dictionary.") else: print("Age does not exist in the dictionary.")
Output:
Age exists in the dictionary.
The code in the example prints “Age exists in the dictionary.” since “age” is a key in my_dict
.
Updating a Dictionary Using the update() Method
The update()
method in Python dictionaries is used to merge the contents of one dictionary into another. It allows you to add, modify, or overwrite key-value pairs in an existing dictionary with those from another dictionary or an iterable of key-value pairs. If a key already exists in the original dictionary, its value is updated; if not, a new key-value pair is added.
The following example demonstrates how the update()
method works with a dictionary argument.
Example:
my_dict = {"name": "Saurus", "age": 30} # Create another dictionary to update from other_dict = {"age": 31, "city": "New York", "job": "Engineer"} # Use update() to merge other_dict into my_dict my_dict.update(other_dict) print(my_dict)
Output:
{'name': 'Saurus', 'age': 31, 'city': 'New York', 'job': 'Engineer'}
In this example, the update()
method merged the contents of other_dict
into my_dict
. It updated the “age” key with the value 31, added the “city” key with the value “New York”, and added the “job” key with the value “Engineer”.
You can also use the update()
method with an iterable of key-value pairs, typically represented as a list of tuples. The next example shows how this works.
Example:
my_dict = {"name": "Saurus", "age": 30} # Create a list of key-value tuples to update from key_value_pairs = [("age", 31), ("city", "New York"), ("job", "Engineer")] # Use update() with the iterable to merge the key-value pairs into my_dict my_dict.update(key_value_pairs) print(my_dict)
Output:
{'name': 'Saurus', 'age': 31, 'city': 'New York', 'job': 'Engineer'}
The result is the same as in the previous example. The update()
method effectively adds, modifies, or overwrites key-value pairs in my_dict
based on the contents of the iterable list, key_value_pairs
.
The update()
method is a powerful way to combine dictionaries or add multiple key-value pairs to an existing dictionary, making it a valuable tool for managing and manipulating dictionary data in Python.
Clearing a Dictionary
The clear()
method in Python dictionaries is used to remove all key-value pairs from a dictionary, effectively emptying it. This method does not return any value, and it modifies the dictionary in place.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} # Use clear() to empty the dictionary my_dict.clear() print(my_dict)
Output:
{}
In this example, the clear()
method removed all the key-value pairs from my_dict
, leaving it as an empty dictionary {}
.
The clear()
method is handy when you need to reuse a dictionary but want to start with an empty one, without having to create a new dictionary object. It’s a straightforward way to reset a dictionary to its initial state.
Finding the Length of a Dictionary
The length of a dictionary is the number of key-value pairs in it, and you can find it using the len()
function.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} print(len(my_dict))
Output:
3
In this example, the value 3 is printed because there are three key-value pairs in my_dict
.
Iterating Over Dictionaries
Python dictionaries offer three methods for extracting information from them using iterators. These methods are items()
, keys()
, and values()
, and they allow you to work with the dictionary key-value pairs, keys, and values, respectively.
Each of these methods provides an iterable object. The following example will let you see what each of the iterables returns using conversion to lists, which are then printed.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} items = my_dict.items() keys = my_dict.keys() values = my_dict.values() print(f"Items: {list(items)}") print(f"Keys: {list(keys)}") print(f"Values: {list(values)}")
Output:
Items: [('name', 'Saurus'), ('age', 30), ('city', 'New York')] Keys: ['name', 'age', 'city'] Values: ['Saurus', 30, 'New York']
As you can see, the key-value pairs items()
returns are tuples with the keys in the first position and the values in the second, while keys()
and values()
return individual-item lists.
Starting with Python 3.7, the order in which the iterators go through the dictionary is the order in which the key-value pairs were added.
Example:
my_dict = {} my_dict["city"] = "New York" my_dict["age"] = 30 my_dict["name"] = "Saurus" print(list(my_dict.items()))
Output:
[('city', 'New York'), ('age', 30), ('name', 'Saurus')
Prior to Python 3.7, the order was undefined and could not be relied upon to be consistent.
Iterating Over Key-Value Pairs in a For Loop
When iterating over the key-value pairs with by the items()
method in a for
loop, it is often convenient to use unpacking. Unpacking is Python syntax used to easily assign items in a collection, such as a tuple, to individual variables.
Example:
my_dict = {"name": "Saurus", "age": 30, "city": "New York"} items = my_dict.items() for key, value in items: print(f"Key: {key}, Value: {value}")
Output:
Key: name, Value: Saurus Key: age, Value: 30 Key: city, Value: New York
In this example, the for
loop iterates over the tuples in the items
iterable. Each tuple contains a pair of values that are individually assigned to the key
and value
loop variables using the unpacking syntax on line 4 of the code.
Summary & Reference for Python Dictionary Basics
A Python dictionary is a powerful data structure used for storing key-value pairs. Unlike list indices, dictionaries keys can be of various data types, making them versatile for organizing and retrieving data efficiently. Dictionaries are implemented using hash tables, providing fast access to values based on their associated keys.
A dictionary literal is defined using curly braces {}
and consists of comma-separated key-value pairs, where each key is separated from its value with a colon.
my_dict = {"name": "Saurus", "age": 30, "city": "New York"}
{}
is the empty dictionary literal.
The dict()
function is a constructor that creates dictionaries from either keyword arguments or iterable objects.
# Using keyword arguments my_dict = dict(name="Saurus", age=30, city="New York") # my_dict --> {'name': 'Saurus', 'age': 30, 'city': 'New York'} # Using iterables my_dict = dict([("name", "Saurus"), ("age", 30), ("city", "New York")]) # my_dict --> {'name': 'Saurus', 'age': 30, 'city': 'New York'}
You can access dictionary values using square brackets with keys or the get()
method. Square brackets raise a KeyError
if the key doesn’t exist, while get()
returns None
or a specified default value if the key is missing.
name = my_dict["name"] # name --> 'Saurus' age = my_dict.get("age") # age --> 30 height = my_dict.get("height", "Default Value") # height --> 'Default Value'
Dictionary keys must be immutable objects, meaning they can’t change after definition. Lists and dictionaries themselves cannot serve as keys due to their mutability, but tuples can.
To change the value associated with a specific key, you can use square brackets to access the key and then assign a new value to it.
my_dict["age"] = 31
You can add a new key-value pair to a dictionary by specifying the new key and its associated value using square brackets.
my_dict["job"] = "Engineer"
The pop()
method removes the dictionary key-value pair associated with the key given as an argument and returns the value. If the key given to pop()
is not in the dictionary, a KeyError
error is generated.
age = my_dict.pop("age") # age --> 30
You can also give pop()
a default value as its second, optional argument. This value is returned if the given key is not in the dictionary.
height = my_dict.pop("height", "Not in Dictionary") # height --> 'Not in Dictionary'
You can delete a key-value pair from a dictionary using the del
statement, specifying the item to delete with the same square bracket notation as for dictionary access. If the key is not in the dictionary, a KeyError
error is generated.
del my_dict["age"]
You can check if a specific key exists in a dictionary using the in
keyword. It returns True
if the key exists and False
if it does not.
if "age" in my_dict: print("Age exists in the dictionary.") else: print("Age does not exist in the dictionary.")
The update()
method is used to merge the contents of one dictionary into another. If a key already exists in the original dictionary, its value is updated; if not, a new key-value pair is added. update()
takes an argument that’s either a dictionary or an iterable with key-value pairs like the dict()
constructor does.
# update() using a dictionary: my_dict = {"name": "Saurus", "age": 30} my_dict.update( {"age": 31, "city": "New York", "job": "Engineer"}) # my_dict --> {'name': 'Saurus', 'age': 31, 'city': 'New York', 'job': 'Engineer'} # update() using an iterable: my_dict = {"name": "Saurus", "age": 30} my_dict.update([("age", 31), ("city", "New York"), ("job", "Engineer")]) # my_dict --> {'name': 'Saurus', 'age': 31, 'city': 'New York', 'job': 'Engineer'}
The clear()
method removes all key-value pairs from a dictionary, effectively emptying it.
my_dict.clear() # my_dict --> {}
You can find the length of a dictionary using the len()
function, which returns the number of key-value pairs in it.
len(my_dict) # --> 3
Iterate over Python dictionaries using the items()
, keys()
and values()
methods, which return iterators to key-value pairs, keys alone, and values alone, respectively. Starting with Python 3.7, the order in which the iterators go through the dictionary is the order in which the key-value pairs were added.
items = list(my_dict.items()) # items --> [('name', 'Saurus'), ('age', 30), ('city', 'New York')] keys = list(my_dict.keys()) # keys --> ['name', 'age', 'city'] values = list(my_dict.values()) # values --> ['Saurus', 30, 'New York']
You can use the unpacking syntax to separate keys from values when iterating over a dictionary with the items()
method.
for key, value in my_dict.items(): print(f"Key: {key}, Value: {value}")