Are you looking to learn how to work with Python dictionaries? This tutorial will cover Python dictionary methods to read, modify and perform other common operations on Python dictionaries.

We’ll start by reviewing the basics of Python dictionaries and then create an example dictionary and modify it using Python dictionary methods.

Let’s get started…

An Overview of Python Dictionaries

Dictionaries are built-in data structures in Python. It lets you store items in key-value pairs—defining an association or mapping between the keys and values.

The keys in a dictionary should be unique (for them to be hashable). You can use the key to look up the value or use built-in methods (you’ll learn them shortly).

When creating a Python dictionary, you can initialize all the key-value pairs or initialize an empty dictionary and then add the key-value pairs.

>>> dict1 = {'language':'Python','like':True}
>>> type(dict1)


# or we can do the following:

>>> dict1 = {}
>>> dict1['language']='Python'
>>> dict1['like']=True

Python Dictionary Methods for Common Operations

Note: To follow along with the code examples, you need to have Python 3.7 or a later version installed.

You can code along in a Python REPL. Or follow along in Geekflare’s online Python editor.

>>> person = {'name':'Alice',
...           'city':'Portland',
...           'interest':'Programming',
...           'profession':'Developer'
...           }

Now that we’ve initialized a Python dictionary, let’s start going over the various dictionary methods.

Get the Dictionary Keys with keys()

One of the common operations when working with a Python dictionary is to access all the keys, values, and key-value pairs. To get the keys of a dictionary, you can call the keys() method as shown:

>>> person.keys()
dict_keys(['name', 'city', 'interest', 'profession'])

Get the Dictionary Values with values()

The values() method returns all the values and is useful when you want to process these values further.

Let’s access all the values in the person dictionary:

>>> person.values()
dict_values(['Alice', 'Portland', 'Programming', 'Developer'])

Get Key-Value Pairs with items()

 The items() method returns a list of key-values tuples. Therefore, calling this method on the person dictionary returns a list of key-value tuples:

>>> person.items()
dict_items([('name', 'Alice'), ('city', 'Portland'), ('interest', 'Programming'), 
           ('profession', 'Developer')])

Get a Shallow Copy with copy()

<img alt="python-dictionary-methods-1" data- data-src="https://kirelos.com/wp-content/uploads/2023/02/echo/1-2-1500×844.png" data- decoding="async" height="422" src="data:image/svg xml,” width=”750″>

The copy() method returns a shallow copy of a Python dictionary.

>>> person_cpy = person.copy()

Here, person_cpy is a shallow copy of the person dictionary. Let us modify this copy by updating the ‘name’ key to ‘Bob’.

>>> person_cpy['name'] = 'Bob'
>>> person_cpy

Now if you examine the contents of the dictionary, you can see that the ‘name’ has been updated to ‘Bob’.

{
 'name': 'Bob', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer'
}

However, the original person dictionary has not been modified.

>>> person
{
 'name': 'Alice', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer'
}

Set Default Values with setdefault()

When working with Python dictionaries, it’s common to run into KeyError exception if the key is not present in the dictionary. Here’s an example when we try to access the ‘age’ key:

>>> person['age']
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'age'

You can avoid such errors by using the built-in methods setdefault() and get() methods instead of accessing the value as above.

The setdefault(key) method returns dict['key'] if the key is present in the dict.

>>> person.setdefault('name')
'Alice'

When the key is not present, it adds the key to the dictionary with the default value of None.

>>> person.setdefault('address')
>>> person

Here, the ‘address’ key is not present in the person dictionary. But we see that it has been added with the default value of None.

{
 'name': 'Alice', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer', 
 'address': None 
}

We can now set the ‘address’ key to some address:

>>> person['address'] = "10, xyz street"
>>> person
{
 'name': 'Alice', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer', 
 'address': '10, xyz street' 
}

You can also specify the value in the method call, as shown:

>>> person.setdefault('country','USA')
'USA'
>>> person

As the ‘country’ key is not originally present in the person dictionary, we see that it has been added with ‘USA’ as the value.

{
 'name': 'Alice', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer', 
 'address': '10, xyz street', 
 'country': 'USA'
}

Get a Specific Value with get()

The get() method returns the value corresponding to the key. It also optionally takes another default value that is returned if the key is not found in the dictionary.

When we try to access the value of the ‘name’ key, we get ‘Alice’ as the key is present in person:

>>> person.get('name')
'Alice'

The person dictionary does not have a ‘gpa’ key. So when we try to get its value, we get nothing at the Python REPL. However, if you print out the value, you’ll get None.

>>> person.get('gpa')
>>> print(person.get('gpa'))
None

But if you provide the optional default value, we get that value instead of None.

>>> person.get('gpa','not found')
'not found'

However, the get() method does not add the ‘gpa’ key to the dictionary.

>>> person
{
 'name': 'Alice', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer', 
 'address': '10, xyz street', 
 'country': 'USA'
}

Understanding setdefault() vs. get()

Though both the setdefault() and get() methods can be used to handle KeyError, let’s summarize the differences from what we’ve learned:

  • dict.setdefault(key,val) adds the key with val as the default value. If val is not provided, the key is added with the default value of None.
  • dict.get(key,val) returns the value corresponding to the key from the Python dictionary. If the key is not present, it returns val (if provided) or None—but does not add the key to the dictionary.

You can also use defaultdict in Python to handle KeyErrors better.

Update Dictionary Contents with update()

You can update an existing Python dictionary using key-value pairs from another dictionary. You can also update with contents of any Python iterable using the update() method.

Let’s define a more_details dictionary. We then update the person dictionary with contents from the more_details dictionary:

>>> more_details = {'hobby':'singing', 'likes':'sweets'}
>>> person.update(more_details)

From the output below, we see that the ‘hobby’ and ‘likes’ keys have been added to the person dictionary.

>>> person
{
 'name': 'Alice', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer', 
 'address': '10, xyz street', 
 'country': 'USA', 
 'hobby': 'singing', 
 'likes': 'sweets'
}

Remove the Last-Added Item with popitem()

<img alt="python-dictionary-methods-2" data- data-src="https://kirelos.com/wp-content/uploads/2023/02/echo/2-2-1500×844.png" data- decoding="async" height="422" src="data:image/svg xml,” width=”750″>

The popitem() dictionary method can be used to remove the last-added key-value pair.

>>> person.popitem()
('likes', 'sweets')

As seen, calling the popitem() method on the person dictionary returns the (‘likes’,’sweets’) key-value pair—the last-added item in the dictionary.

It also removes the key-value pair. You can confirm this by examining the contents of the dictionary:

>>> person
{
 'name': 'Alice', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer', 
 'address': '10, xyz street', 
 'country': 'USA', 
 'hobby': 'singing'
}

Remove a Dictionary Item with pop()

We know that the popitem() dictionary method removes and returns the last key-value pair in a Python dictionary. However, we may sometimes need to remove other items—other than the last-added key-value pair too.

To do this, we can use the Python dictionary method pop(): using .pop(key) on the dictionary returns the value corresponding to the key and also removes the key-value pair from the dictionary.

Here’s an example:

>>> person.pop('hobby')
'singing'

As we popped the item corresponding to the key ‘hobby’, we see that it’s no longer present in the dictionary.

>>> person
{
 'name': 'Alice', 
 'city': 'Portland', 
 'interest': 'Programming', 
 'profession': 'Developer', 
 'address': '10, xyz street', 
 'country': 'USA'
}

If we pass in a key that does not exist, we run into KeyError exception, as shown:

>>> person.pop('age')
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'age'

Here, we run into a KeyError exception as the ‘age’ key is not present in the person dictionary.

Unlike the list pop() method that removes the last item by default, the dictionary pop() method requires a key. If you do not specify a key in the method, we’ll run into errors.

>>> person.pop()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: pop expected at least 1 argument, got 0

Delete All Dictionary Items with clear()

The dictionary pop() and popitem() methods remove one key-value pair at a time. If you want to delete all the items in a dictionary, you can use the clear() method.

>>> person.clear()
>>> person
{}

As seen, calling the clear() method on the person dictionary removes all key-value pairs and the person dictionary is now empty.

Summary of Python Dictionary Methods

<img alt="python-dictionary-methods-3" data- data-src="https://kirelos.com/wp-content/uploads/2023/02/echo/3-2-1500×844.png" data- decoding="async" height="422" src="data:image/svg xml,” width=”750″>

Here’s a quick review of the Python dictionary methods we’ve learned.

Method Syntax Description
keys() dict1.keys() Returns the keys of dict1
values() dict1.values() Returns the values of dict1
items() dict1.items() Returns a list of all key-value pairs in dict1
copy() dict1.copy() Returns a shallow copy of dict1
setdefault() dict1.setdefault(key, default_value) – Adds key with the optional default_value as the key to dict1 (when not specified, the default value is None)

– Returns dict1[key] if the key is already present
get() dict1.get(key,default_value) – Returns dict1[key] if key is present in dict1; Else, returns the default_value

– If key is not present in dict1 and default_value is not specified, returns None
update() dict1.update(iterable1) Updates dict1 with key-value pairs from iterable1
popitem() dict1.popitem() Removes and returns the last key-value pair from dict1
pop() dict1.pop(key) – Removes and returns the value corresponding to the key: dict1[key]

– Raises a KeyError if the key is not present in dict1
clear() dict1.clear() Deletes all items from dict1

Conclusion

You’ve learned how to use common methods to perform read, update, and delete operations on Python dictionaries. In addition, you also learned how the get() and the setdefault() methods can be used to handle KeyError exceptions by returning a default value and adding an entry with a default value to the Python dictionary, respectively. You can also sort a Python dictionary by key or by value.

Next, check out the list of useful Python list methods. Happy coding!