Alongside the Python list, the dictionary is the most commonly used data storage structure in Python. Dictionaries allow you to store numeric and text-based data as a series of key-value pairs, so the data can be retained, looked up, and retrieved in your code when you need it.
As dictionaries support nesting, and embedding other lists and dictionaries within, they can be used to store quite complex data and allow you to change the values, look up or search for data within the dictionary, and loop over the contents to manipulate or display them. They’re really useful. Here’s a quick guide to the basics.
Dictionaries are fairly straightforward to use, once you understand the basic concepts of how they work. They’re effectively the equivalent of the associative arrays or hashes found in other languages, such as PHP, and are extremely flexible and useful to use in your Python code. Here the key features of Python dictionaries you need to know.
Feature | Description |
---|---|
Key-value pairs | Dictionaries use key-value pairs, like "language": "python" instead of the indexes used in lists. This means you can edit a value, delete a value, find, or return a value by looking for its key, i.e. language , which is easier than a list. |
Unordered | Dictionaries are unordered. The items within aren't in order so have no index. You can store and construct them as you wish. |
Updatable | Dictionaries can be updated using their keys after creating, allowing you to edit or delete values or key-value pairs, or add new elements to the dictionary. |
Unique keys | Since there's no index, the key needs to be unique. If you duplicate a key it will overwrite the data in the previous key sharing its name. Keys can be numeric, i.e. 1 or strings, i.e. name . |
Nesting | A dictionary can consist of a simple set of key-value pairs, or the value can contain a list or a dictionary, or a list of lists, or a list of dictionaries, or any other combination you may require. |
Create an empty dictionary
Just as an empty Python list can be created by writing name = []
an empty Python dictionary can be created by writing name = {}
. The curly brackets or braces denote a dictionary, while square brackets denote a list.
pages = {}
pages
{}
Create a dictionary with numeric keys
There are several ways to populate a Python dictionary with values. One common technique is to manually construct the dictionary and assign it to a variable. In the example below we’re creating and populating a dictionary with numeric keys and assigning it some string values and storing it in a variable called pages
. Note the lack of quotes around the integer key names.
pages = {
1: 'Home',
2: 'Checkout',
3: 'Basket'
}
pages
{1: 'Home', 2: 'Checkout', 3: 'Basket'}
Create a dictionary with non-numeric keys
It’s more common to create a dictionary with non-numeric keys. To manually create a dictionary with non-numeric keys you can use the same approach, you just need to replace the integers with strings and ensure they’re encapsulated in quotes.
pages = {
'home': '/',
'checkout': '/checkout',
'basket': '/basket'
}
pages
{'home': '/', 'checkout': '/checkout', 'basket': '/basket'}
Create a dictionary using dict()
The dict()
function can also be used to construct a Python dictionary from comma-separated key=value pairs. Here’s the same dictionary we created in the step before made using dict()
.
pages = dict(home = '/', checkout = '/checkout', basket = '/basket')
pages
{'home': '/', 'checkout': '/checkout', 'basket': '/basket'}
Create a nested dictionary of dictionaries
Dictionaries really come into their own when you start nesting them. Dictionaries can be stored in other dictionaries, or inside lists, or virtually any combination of these, making them an extremely flexible data structure. Let’s manually create a dictionary called customers
that contains a numeric key and contains individual dictionaries for each customer.
customers = {
1: {
'name': 'Bob',
'orders': 12,
'total_spend': 129.23
},
2: {
'name': 'Fred',
'orders': 2,
'total_spend': 28.34
}
}
customers
{1: {'name': 'Bob', 'orders': 12, 'total_spend': 129.23},
2: {'name': 'Fred', 'orders': 2, 'total_spend': 28.34}}
Add an item to a dictionary by assigning an index key
If you have a simple un-nested dictionary, the easiest way to add a new value is to define a new index key and assign a value to it. For example, pages['Contact'] = '/contact'
will extend the pages
dictionary and add an index key called Contact
and assign the value /contact
.
pages = {
'home': '/',
'checkout': '/checkout',
'basket': '/basket'
}
pages['contact'] = '/contact'
pages
{'home': '/',
'checkout': '/checkout',
'basket': '/basket',
'contact': '/contact'}
Update an un-nested dictionary value
The update()
function allows you to change, overwrite, or update the value in a dictionary. The function takes a new dictionary containing the key and the value you wish to replace the current value with. pages.update({'basket': '/new-basket'})
will update the value /basket
in the above dictionary with /new-basket
.
pages.update({'basket': '/new-basket'})
pages
{'home': '/',
'checkout': '/checkout',
'basket': '/new-basket',
'contact': '/contact'}
Access dictionary values using their key
Python dictionary values can be accessed by calling their index key in square brackets. For example, to access the values stored in the customers
dictionary in index 1
we would use customers[1]
. To access a value in the pages
dictionary, which has a non-numeric key, we would use pages['contact']
.
customers[1]
{'name': 'Bob', 'orders': 12, 'total_spend': 129.23}
pages['contact']
'/contact'
Access nested dictionary values using their key
For a nested dictionary, you can access dictionary values by using multiple dictionary keys. For example, to extract the name
of the customer in index 1
of the customers
dictionary we would use customers[1]['name']
.
customers[1]['name']
'Bob'
Access dictionary values using get()
The other approach to extracting dictionary values is to use the get()
function. To find the value stored in the contact
key using get()
we would use pages.get('contact')
, which is the equivalent of pages['contact']
. While customers.get(1)
is the equivalent of customers[1]
.
pages.get('contact')
'/contact'
customers.get(1)
{'name': 'Bob', 'orders': 12, 'total_spend': 129.23}
Access nested dictionary values using get()
You can also use get()
to access nested dictionary values. customers.get(1).get('orders')
will return the orders
value stored in the index 1
of the customers
dictionary.
customers.get(1).get('orders')
12
Matt Clarke, Sunday, February 06, 2022