© BEST-BACKGROUNDS / Shutterstock.com

Dictionaries are one of the most essential data structures in Python, and understanding how to use them can unlock a world of possibilities for your programming projects. They are especially useful when dealing with large amounts of data or complex data structures, such as nested lists or objects. Whether you’re a beginner or an experienced programmer, this article will provide you with a comprehensive guide to dictionaries in Python, including detailed explanations and examples of how to define and manipulate them. Let’s dive right into!

What Exactly is a Dictionary in Python

A dictionary is an unordered collection of key-value pairs, where each key is unique. The key is used to identify the associated value, which can be any type of object, including strings, integers, floats, booleans, lists, or even other dictionaries. Dictionaries are similar to the data structures sometimes referred to as “hash maps” or “associative arrays” in other programming languages.

Unlike other data structures in Python, such as tuples, which have an order associated with them, dictionaries do not have any inherent order. Instead, a dictionary stores each item based on its key value pairings. That’s what makes them incredibly versatile and powerful in letting us quickly access specific elements within our data structure without having to iterate over every item.

Also, dictionaries, unlike tuples, are mutable, meaning that you can add, modify, and remove items from them after you have created them. This makes dictionaries incredibly powerful and flexible data structures for a wide range of programming tasks.

In the next section, we’ll look at how to manipulate dictionaries and their elements.

How to Define/Create a Dictionary in Python

Dictionaries are incredibly efficient in storing and retrieving data. To create a new dictionary in Python, you can use the curly braces {} and separate each key-value pair with a colon. The key-value pairs/elements in a dictionary are separated by commas like so:

my_dict = {“key1”: “value1”, “key2”: “value2”, “key3”: “value3”}

Here is an example of a Python dictionary used to store a list of fruits:

my_dict = {“apple”: 3, “banana”: 2, “cherry”: 5}

Here, we have defined a dictionary called my_dict, which contains three key-value pairs. The keys are “apple”, “banana”, and “cherry”, and the values associated with these keys are 3, 2, and 5 respectively. It’s important to note that keys must be unique; if you try to add another item with the same key it will overwrite the existing one instead of creating a new entry with a different value.

You can also create an empty dictionary by simply using two sets of curly braces {} without any items inside like so:

 my_empty_dict = {}

Manipulating a Dictionary in Python

Adding Elements to a Python Dictionary

Once you have created your dictionary, you can start adding elements. To do so, simply specify its key, followed by its associated value within these brackets. 

Let’s add some more items to our previous example:

my_dict[“pear”] = 4    # Adding an integer

my_dict[“orange”] = “none”   # Adding a string

Our dictionary now has 5 elements:

my_dict = {“apple”: 3, “banana”: 2, “cherry”: 5, “pear”: 4, “orange”: “none”}

Please follow proper syntax rules when adding different data types (for example, integers must be written without quotation marks, as seen above). Now let’s look at how we can read elements from our newly populated dictionary.

Reading Elements From a Python Dictionary

Reading elements from a Python dictionary is just as easy as writing them; all you need do is specify the desired key within square brackets [] following your dictionary name:

print(my_dict[“banana”])    # Outputs 2

If you try accessing an element that doesn’t exist, Python will throw up an error message telling you what went wrong. Here’s an example:

print(my_dict[ “grape”])     # Outputs KeyError: grape

This makes debugging much easier since we know exactly what needs fixing.

How to Update a Dictionary in Python

Updating elements within your Python dictionary involves two steps; firstly specifying which element needs updating, and secondly providing the new value that needs to be assigned.

The syntax for this is as follows:

my_dict[key] = new_value

For example, if we want to update the value associated with the key “cherry”, we can do so by using this code:

my_dict[“cherry”] = 8

It’s important to note that if you try to update an element which doesn’t exist within your dictionary, it will automatically create it for you. For example, if we use the code below in our example dictionary:

my_dict[“guava”] = 2

It will create an additional element in my_dict with the key “guava” and the integer value 2.

Removing Elements From a Dictionary

Removing elements from a Python dictionary involves using the del keyword. The syntax for removing an element from a dictionary is as follows:

del my_dict[key]

For example, to remove the element associated with the key “apple” in my_dict, we can do so using:

del my_dict[“apple”]

You can also remove elements from a dictionary using the pop() method. The pop() method allows you to remove a specific element by its associated key and then return the removed element.

Using our previous example:

my_dict.pop(“pear”) #removes the element with key “pear” and returns the value 4

Let us now look at nested dictionaries.

Nested Dictionaries in Python

Nested dictionaries are used to store more complex data structures, such as collections of objects or other dictionaries. The syntax for nesting a dictionary within another is as follows:

my_dict = {

         “key1”: {“nested_key1”: “value1”, “nested_key2”: “value2”}, 

         “key2”: {“nested_key3”: “value3”, “nested_key4”: “value4”}


They are incredibly useful for organizing and manipulating data, such as when you need to store multiple pieces of related information about a single object. 

Let’s take our example dictionary of fruits from earlier and nest it into a larger dictionary called groceries

groceries = {“fruits”: my_dict}

Here we have created a new dictionary called groceries and added the my_dict dictionary as an element with the key “fruits”. 

We can also manipulate nested dictionaries using CRUD operations (Create Read Update Delete) as we did before. Let’s see how this works in practice. 

Creating Nested Elements in a Dictionary

To add additional elements to a nested dictionary, you can use the same syntax as before; simply specify the desired key, followed by its associated value within curly brackets {}. For example, if we wanted to add an element for “grapes” with a value of 6 to our grocery list, we could do so using this code:

 groceries[“fruits”][“grapes”] = 6   # Adds grapes with the value 6 

Reading Nested Elements From a Dictionary

To access elements within the nested dictionary, we use two sets of square brackets [] with the respective identifying keys. For example, if we want to access the value associated with the key “cherry” in the nested dictionary (my_dict), we would use this code: 

print(groceries[“fruits”][“cherry”])    # Outputs 5

Updating Nested Elements in a Dictionary

To update an element in a nested dictionary, you can use the same syntax as before. Simply specify the desired key, followed by its new associated value within square brackets []. For example, if we want to update the value associated with the key “apple”, we can do so using this code: 

 groceries[“fruits”][“apple”] = 4    # Updates apple’s value to 4

Removing Nested Elements From a Dictionary

Removing elements from a nested dictionary is just as easy. All you need to do is use the del keyword, followed by both keys within two sets of square brackets. For example, if we want to remove the element with the key “banana”, we can do so using this code: 

 del groceries[“fruits”][“banana”]    # Removes banana from my_dict

You can also use the pop method with nested dictionaries:

groceries[“fruits”].pop(“banana”) # Removes banana from my_dict

It’s important to remember that when manipulating an element inside a nested dictionary, you must specify all keys necessary to reference the element (just like you would in a multi-dimensional array). If any key is incorrect or missing, the element will not be manipulated in the way you intended.

Other Dictionary Methods

Python dictionaries also have several built-in methods that can help you manipulate and retrieve data from them. Some of the most useful ones are .keys(), .values(), and .items()

The .keys() method returns a list of all the keys in a dictionary, while the .values() method returns a list of all the values in a dictionary.  

For example, if we want to print out all the keys in our groceries dictionary, we can do so using this code: 

print(groceries.keys())    # Outputs [fruits

The .items() method returns all the key-value pairs for each element of the dictionary as tuples in a list.

Wrapping Up

Dictionaries are one of the most essential data structures in Python and mastering the basic methods we’ve looked at would go a long way in helping you in unlocking their actual power in Python. They are incredibly versatile and can be used for a wide range of tasks, from simple data storage to complex data manipulation and analysis. And with the ability to search for specific values or keys quickly, without having to loop through every element of the collection, dictionaries are a sure way to take your Python game to the next level!

Dictionary in Python, and How to Use It (With Examples) FAQs (Frequently Asked Questions) 

What's a Python dictionary?

A Python dictionary is a collection of key-value pairs. It is similar to an array, but instead of storing values in an indexed list, it stores them in a key-value format, where the keys are strings or integers and the values can be any type. Dictionaries are also known as associative arrays or hash maps.

How can I create a dictionary from other data types in Python?

You can use the dict() constructor to create dictionaries from other data types such as lists or tuples. For example, if you have a list of tuples like this: my_list = [(‘key1’, ‘value1’), (‘key2’, ‘value2’)], you can use the dict() constructor to create a dictionary out of it like so:
my_dict = dict(my_list).

How do I loop through a dictionary?

Looping through a dictionary requires two steps: first you need to iterate over its keys using either a for loop or while loop; then you need to access each element’s value using its associated key inside the loop body. For example:

my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}

for key in my_dict:


Which is better between pop() and del when it comes to removing elements from a dictionary in Python?

While that mostly depends on what you are trying to accomplish, if you want to keep the removed item for further use, then pop() would be a better option. However, if you want to delete an item without retrieving it, then del would be more suitable. .pop() is also slower since it requires a function call instead of a primitive operation.

What are some basic Python dictionary Do's and Don'ts?

Do: Use a dictionary when you need to store key-value pairs in an efficient manner. Make sure your keys are unique and immutable.

Don’t: Use a dictionary if you need to store data in a particular order; use a list instead.

About the Author

More from History-Computer

  • Python Docs Available here: https://docs.python.org/3/tutorial/datastructures.html
  • W3Schools Available here: https://www.w3schools.com/python/python_ref_dictionary.asp
  • Shittu Olumide Available here: https://www.freecodecamp.org/news/python-remove-key-from-dictionary/
  • Codecademy Available here: https://www.codecademy.com/learn/dacp-python-fundamentals/modules/dscp-python-dictionaries/cheatsheet
  • Bijay Kumar Available here: https://pythonguides.com/python-dictionary-pop/