Back to Freecodecamp

What Are Dictionaries, and How Do They Work?

curriculum/challenges/english/blocks/lecture-working-with-dictionaries-and-sets/683ec7a722bc7b67c1132bd3.md

latest7.8 KB
Original Source

--description--

In Python, dictionaries are built-in data structures that store collections of key-value pairs. They work very similarly to real dictionaries, where you search for a word to find its corresponding meaning.

With Python dictionaries, you use a key to find its corresponding value. You should use dictionaries when you need to associate values to unique keys. This is helpful when you need to find a value fast based on the key, and when you need to represent structured data.

This is the general syntax of a Python dictionary:

python
dictionary = {
    key1: value1,
    key2: value2
}

First, we find the variable that holds the dictionary. You don't necessarily need to assign the dictionary to a variable, but it's very common to do this to keep it in memory and use it later in the code.

Then that's followed by curly braces, which are sometimes called curly brackets. And within the curly braces, there are key-value pairs.

Each key is associated with a value, so you can use the key to access that value. After each value, except the last one, there's a comma to separate the different key-value pairs. Keys must be unique in the dictionary, and they must be an immutable data type. However, the values can be repeated, and they can be of any data type.

Here we have an example of a dictionary that stores information about a Margherita pizza recipe:

python
pizza = {
    'name': 'Margherita Pizza',
    'price': 8.9,
    'calories_per_slice': 250,
    'toppings': ['mozzarella', 'basil']
}

The dictionary is assigned to the pizza variable. It has four key-value pairs: name, price, calories_per_slice, and toppings.

Another alternative would be using the dict() constructor, which builds the dictionary from a sequence of key-value pairs.

This would be the equivalent syntax for our pizza example. We pass a list of tuples as argument to the dict() constructor. These tuples contain the key as the first element and the value as the second element.

python
pizza = dict([('name', 'Margherita Pizza'), ('price', 8.9), ('calories_per_slice', 250), ('toppings', ['mozzarella', 'basil'])])

To access the value of a key-value pair, you can use this syntax, known as bracket notation. It's the name of the variable that holds the dictionary, followed by square brackets, and the key you want to access within the square brackets:

python
dictionary[key]

In our pizza example, if you want to access the value of name, you would write the name of the variable, pizza, followed by square brackets, and the key, name, within quotes:

python
pizza['name']

This will evaluate to:

python
'Margherita Pizza'

To update a value, you just need to add the assignment operator, followed by the new value.

If the key doesn't exist in the dictionary, a new key-value pair will be created. In recent versions of Python, dictionaries preserve the order of insertion. This is helpful when you need to iterate over the dictionary:

python
pizza['name'] = 'Margherita'

Now the value of the key name is 'Margherita':

python
print(pizza['name']) # 'Margherita'

Dictionaries also have helpful methods to perform common operations.

The .get() method retrieves the value associated with a key. It's similar to the bracket notation that we just used, but its advantage is that you can set a default value, so you won't get an error if the key doesn't exist:

python
dictionary.get(key, default)

In this example, if the toppings key doesn't exist, it will return an empty list, which is the default value that we are passing here as the second argument. But if toppings does exist, it will return that value:

python
pizza.get('toppings', []) # ['mozzarella', 'basil']

The .keys() and .values() methods return a view object with all the keys and values in the dictionary, respectively:

python
pizza.keys()
# dict_keys(['name', 'price', 'calories_per_slice'])

pizza.values()
# dict_values(['Margherita Pizza', 8.9, 250])

A view object is just a way to see the content of a dictionary without creating a separate copy of the data.

The .items() method returns a view object with all the key-value pairs in the dictionary, including both the keys and the values:

python
pizza.items()
# dict_items([('name', 'Margherita Pizza'), ('price', 8.9), ('calories_per_slice', 250)])

The .clear() method removes all the key-value pairs from the dictionary:

python
pizza.clear()

The .pop() method removes the key-value pair with the key that you specify as the first argument and returns its value. If the key doesn't exist, it returns the default value that you specify as the second argument. If the key doesn't exist and you don't pass a default value, a KeyError is raised:

python
pizza.pop('price', 10)
pizza.pop('total_price') # KeyError

In Python 3.7 and more recent versions, the .popitem() method removes the last inserted item:

python
pizza.popitem()

And finally, the .update() method updates the key-value pairs with the key-value pairs of another dictionary. If they have keys in common, their values are overwritten.

In this example, we are updating the pizza dictionary. The price key exists in both of them, so its value will be replaced with 15.

But total_time is new, so it will be added to the pizza dictionary as a new key-value pair:

python
pizza.update({ 'price': 15, 'total_time': 25 })

This is the new dictionary with the updated price and the new total_time. Notice how the price is now 15 and total_time is a new key-value pair:

python
{
    'name': 'Margherita Pizza', 
    'price': 15, 
    'calories_per_slice': 250, 
    'toppings': ['mozzarella', 'basil'], 
    'total_time': 25
}

These are some of the most commonly used dictionary methods, but there are many more. Choosing the right one can be helpful for performing complex operations efficiently.

--questions--

--text--

How are elements primarily organized and accessed in a Python dictionary?

--answers--

Using sequential indices, like a list.

--feedback--

Think about the core characteristic that distinguishes dictionaries from lists and tuples.


Using key-value pairs, where keys are unique.


Using a tree-like structure, similar to file systems.

--feedback--

Think about the core characteristic that distinguishes dictionaries from lists and tuples.


Using a linked list, where elements point to the next.

--feedback--

Think about the core characteristic that distinguishes dictionaries from lists and tuples.

--video-solution--

2

--text--

What is the primary characteristic of a Python dictionary that makes it different from a list or tuple?

--answers--

Dictionaries create duplicates of all key-value pairs.

--feedback--

Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.


Dictionaries are mutable.

--feedback--

Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.


Dictionaries allow fast lookups using keys.


Dictionaries can store duplicate values.

--feedback--

Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.

--video-solution--

3

--text--

Which dictionary method is used to retrieve a value associated with a key, and provide a default value if the key is not found?

--answers--

.keys()

--feedback--

Think about which method is designed for safe retrieval of values without throwing an error.


.values()

--feedback--

Think about which method is designed for safe retrieval of values without throwing an error.


.pop()

--feedback--

Think about which method is designed for safe retrieval of values without throwing an error.


.get()

--video-solution--

4