Python Dictionary – How to Perform CRUD Operations on dicts in Python

One of the most important composite data types in Python is the dictionary. It’s a collection you use to store data in {key:value} pairs.

Dictionaries are ordered and mutable, and they cannot store duplicate data. Just keep in mind that before Python 3.6, dictionaries were unordered.

Alright, let’s dive in and learn more about how they work.

How to create a dictionary in Python

As we know, a dictionary consists of a collection of {key:value} pairs. A colon (:) separates each key from its associated value.

We can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}).

my_dict = { "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"]
}

In the above example, Name, Roll, and Subjects are the keys of the dictionary my_dict. Ashutosh Krishna, 23, and ["OS", "CN", "DBMS"] are their respective values.

We can also declare a dictionary using the built-in dict() function like this:

my_dict = dict({ "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"]
})

A list of tuples works well for this:

my_dict = dict([ ("Name", "Ashutosh Krishna"), ("Roll", 23), ("Subjects", ["OS", "CN", "DBMS"])
])

They can also be specified as keyword arguments.

my_dict = dict( Name="Ashutosh Krishna", Roll=23, Subjects=["OS", "CN", "DBMS"]
)

How to access dictionary values in Python

You can’t access dictionary values using the index.

my_dict = { "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"]
} print(my_dict[1])

If you try to do this, it will throw a KeyError like this:

Traceback (most recent call last): File "C:UsersashutDesktopTesthellotest.py", line 7, in <module> print(my_dict[1])
KeyError: 1

Notice that the exception is called KeyError. Does that mean the dictionary values can be accessed using the keys? Yes, you got it right!

You can get a value from a dictionary by specifying its corresponding key in square brackets ([]).

>>> my_dict['Name'] 'Ashutosh Krishna'
>>> my_dict['Subjects'] ['OS', 'CN', 'DBMS']

If a key doesn’t exist in the dictionary, we get a KeyError exception as we saw above.

>>> my_dict['College'] Traceback (most recent call last): File "<stdin>", line 1, in <module>
KeyError: 'College'

But we can also avoid this error using the get() function.

>>> my_dict.get('College')
>>> 

If the key exists in the dictionary, it will retrieve the corresponding value. But if it doesn’t exist, it won’t throw an error.

How to update a dictionary in Python

Dictionaries are mutable, which means they can be modified. We can add a new {key:value} pair or modify existing ones.

Adding a new item in the dictionary is quite easy using the assignment operator, like this:

>>> my_dict['College'] = 'NSEC'
>>> my_dict {'Name': 'Ashutosh Krishna', 'Roll': 23, 'Subjects': ['OS', 'CN', 'DBMS'], 'College': 'NSEC'}

If the key is already present in the dictionary, it will update the value of that key.

>>> my_dict['Roll'] = 35
>>> my_dict
{'Name': 'Ashutosh Krishna', 'Roll': 35, 'Subjects': ['OS', 'CN', 'DBMS'], 'College': 'NSEC'}

How to update a dict using the update() method

We can also update the dictionary using the built-in update() method like this:

>>> my_dict
{'Name': 'Ashutosh Krishna', 'Roll': 35, 'Subjects': ['OS', 'CN', 'DBMS'], 'College': 'NSEC'}
>>> another_dict = {'Branch': 'IT'}
>>> my_dict.update(another_dict)
>>> my_dict
{'Name': 'Ashutosh Krishna', 'Roll': 35, 'Subjects': ['OS', 'CN', 'DBMS'], 'College': 'NSEC', 'Branch': 'IT'}
>>>

The update() method takes either a dictionary or an iterable object of key/value pairs (generally tuples).

>>> my_dict.update(Branch='CSE') >>> my_dict
{'Name': 'Ashutosh Krishna', 'Roll': 35, 'Subjects': ['OS', 'CN', 'DBMS'], 'College': 'NSEC', 'Branch': 'CSE'}

How to remove elements from dictionary in Python

There are several ways to remove elements from a Python dictionary.

How to remove elements from a dict with the pop() method

We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.

>>> roll = my_dict.pop('Roll') >>> roll
35
>>> my_dict
{'Name': 'Ashutosh Krishna', 'Subjects': ['OS', 'CN', 'DBMS'], 'College': 'NSEC', 'Branch': 'CSE'}

How to remove an item from a dict with the popitem() method

The popitem() removes the last key-value pair and returns it as a tuple:

>>> my_dict.popitem()
('Branch', 'CSE')
>>> my_dict
{'Name': 'Ashutosh Krishna', 'Subjects': ['OS', 'CN', 'DBMS'], 'College': 'NSEC'}

How to remove an item from a dict with the del keyword

You can use the del keyword to delete a particular {key:value} pair or even the entire dictionary.

>>> del my_dict['Subjects'] >>> my_dict
{'Name': 'Ashutosh Krishna', 'College': 'NSEC'}
>>> del my_dict
>>> my_dict
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'my_dict' is not defined

How to remove an item from a dict with the clear() method

The clear method clears all the {key:value} pairs in the dictionary.

>>> my_dict
{'Name': 'Ashutosh Krishna', 'Roll': 23, 'Subjects': ['OS', 'CN', 'DBMS']}
>>> my_dict.clear()
>>> my_dict
{}

Notice that after the clear() method is called, printing the dictionary doesn’t throw an error because the clear() method doesn’t remove the dictionary. But the del keyword removes the dictionary too. That’s why we get a NameError in that case.

Dictionary Operators and Built-in Functions

Let’s talk about two important operators and built-in functions we can use with dictionaries.

len() function

The len() function returns the number of key-value pairs in a dictionary:

>>> my_dict
{'Name': 'Ashutosh Krishna', 'Roll': 23, 'Subjects': ['OS', 'CN', 'DBMS']}
>>> len(my_dict)
3

sorted() function

The sorted() function sorts the elements of a given iterable in a specific order (ascending or descending) and returns it as a list.

>>> sorted(my_dict)
['Name', 'Roll', 'Subjects']

in operator

You can use the in operator to check whether a key is present in the dictionary or not.

>>> 'Roll' in my_dict
True
>>> 'College' in my_dict
False

Built-in Dictionary Methods

There are various built-in methods available in a Python dictionary. We have discussed few of them earlier such as clear(), pop() ,and popitem(). Let’s see some other methods too.

Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary’s items in (key, value) format.
keys() Returns a new object of the dictionary’s keys.
pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary’s values

How to iterate through a dictionary

By default, when we use a for loop to iterate over a dictionary, we get the keys:

my_dict = { "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"]
} for item in my_dict: print(item)

Output:

Name
Roll
Subjects

We can also iterate over a dictionary in the following ways:

How to iterate through a dictionary using the items() method

When we use the items() method to iterate over a dictionary, it returns a tuple of key and value in each iteration. Thus we can directly get the key and value in this case:

my_dict = { "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"]
} for key, value in my_dict.items(): print(key, value)

Output:

Name Ashutosh Krishna
Roll 23
Subjects ['OS', 'CN', 'DBMS']

How to iterate through a dictionary using keys()

In this case, we get the key in each iteration.

my_dict = { "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"]
} for key in my_dict.keys(): print(key)

Output:

Name
Roll
Subjects

How to iterate through a dictionary using values()

In this case, we get the values of the dictionary directly.

my_dict = { "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"]
} for value in my_dict.values(): print(value)

Output:

Ashutosh Krishna
23
['OS', 'CN', 'DBMS']

How to merge dictionaries in Python

We often need to merge dictionaries in Python. I’ve written a separate article on this topic, which you can read here.

Wrapping Up

In this article, we learned what Python dictionaries are and how to perform CRUD operations on them. We also saw several methods and functions associated with them.

I hope you enjoyed it – and thanks for reading!

Subscribe to my newsletter

Posted by Contributor