Mastering Dictionaries in Python: The Ultimate Guide

Table of Contents

Introduction

Greetings, everyone! Today, we’ll be delving into one of the most powerful and frequently used data types in Python – dictionaries. If you’ve been following our previous posts, you’ve already learned about some other important data types in Python such as numeric datatypes, string datatypes, lists, and tuples. If you haven’t read them yet, we highly recommend you to check them out.

 

So, without further ado, let’s dive into the wonderful world of dictionaries!

Dictionaries in python

Dictionaries are a powerful and frequently used data type in Python. They allow you to store and retrieve data using a key-value pair system. In other words, you can map unique keys to specific values in a dictionary. This makes dictionaries incredibly useful in a wide range of Python applications.

00

You guys can think of a dictionary as a collection of key-value pairs just like the ones that we see at our houses or at the library. You can think of keys as unique identifiers that allow you to access the corresponding values in the dictionary. This means that dictionaries are great for tasks that require you to quickly access specific pieces of data based on a key.

 

Dictionaries are a built-in data type in Python, and they are incredibly versatile. You can use them to store a wide range of data types, including strings, numbers, and even other data structures like lists or other dictionaries.

 

So now you must be wondering, where do we use dictionaries? Well, dictionaries have multiple use cases in programming, some of the most significant ones being:

 

Storing configuration settings: 

Dictionaries are often used to store configuration settings for an application. For example, you could store settings such as the path to a file, the default font size for text, or the background colour for a user interface.

 

Mapping user input:

Dictionaries can be used to map user input to specific functions or commands. For example, if a user types “open file”, you could use a dictionary to map that input to a specific function that opens a file.

 
Storing data from APIs:

Dictionaries are often used to store data from APIs in a structured way. For example, you could use a dictionary to store information about a specific user returned from a social media API.

 

Implementing Caches:

Dictionaries can be used to implement caches in a program. For example, you could use a dictionary to store the results of expensive calculations so that you can quickly retrieve them later without having to recalculate them.

Components of a dictionary

In the previous section, we discussed that a dictionary is a collection of key-value pairs. Now, let’s take a closer look at what these components represent and their general nature.

 

Here’s an example of a dictionary in Python:

my_dict = {“name”: “John”, “age”: 25, “city”: “New York”}

01

In this example, we have a dictionary with three key-value pairs. 

 

The keys are:

  1. “name”
  2. “age”
  3. “city”

 

And the values are:

  1. “John”
  2. 25 
  3. “New York”
 
Keys:

Keys are the unique identifiers in a dictionary. They must be immutable, meaning they cannot be changed once they are created. Common examples of immutable data types used as keys include strings, numbers, and tuples.

 
Values:

Values are the data associated with a specific key in a dictionary. They can be of any data type, including strings, numbers, lists, and even other dictionaries.

 

Even though the keys in dictionaries are immutable dictionaries as an entity is mutable, meaning that you can add, remove, or modify key-value pairs after the dictionary is created.

Properties of Dictionary in Python

1. Syntax of a dictionary data type:

 

  • A dictionary is a collection of key-value pairs separated by a comma and enclosed in curly braces.

{key1:value1, key2:value2, key3:value3, …}

  • Each key-value pair is called an item.

{item1, item2, item3, item4, …}

  • All items are enclosed in curly braces ({}) and separated by a comma.
  • The key and value in a pair are separated by a colon (:).
  • Keys of the dictionary cannot be duplicated, whereas values can be duplicated.
  • Keys of a dictionary cannot be updated or changed, but the value pertaining to a key can be updated or changed.

 

2. Dictionary is not a sequence:

 

  • Indexing and slicing are not possible in a dictionary.
  • Concatenation and repetition are also not possible

 

3. Dictionary is a mutable data type:
  • Dictionary as a whole is a mutable data type, i.e., its values can be updated and changed.

 

4. Data types for key and value:
  • Keys can only be immutable data types and cannot be mutable.
  • Values can be any type; mutable or immutable.

Creating a Dictionary

Creating a dictionary in Python is relatively simple. You can declare a dictionary using the following syntax:

 

Syntax: dictionary_name = {key1: value1, key2: value2, key3: value3}

 

Here dictionary_name is the name of the dictionary, and key1, key2, key3 are the keys associated with their respective values value1, value2, value3.\


For example, let’s create a dictionary my_dict containing the ages of three people:

02

In this case, “John“, “Mary“, and “Bob” are the keys, and 25, 27, and 21 are the corresponding values.

 

We’ve just seen the classical method of creating a dictionary in Python. However, there are other methods that you can use to create dictionaries as well. Let’s take a look at some of  them.

 

1. Empty Dictionary

You can create an empty dictionary and add key-value pairs to it later, here is an example:

03

This approach is useful when you don’t know all the key-value pairs in advance or want to add them dynamically.

2. Using dict() constructor

As we’ve seen in our previous blogs, you can also create a dictionary in Python by passing key-value pairs as arguments to the dict() constructor, just like you can do with lists and tuples.

 

Syntax: my_dict = dict(key1=value1, key2=value2, key3=value3)

Example:

04

We can also create a dictionary by passing a list of tuples, where each tuple contains a key-value pair, to the dict() constructor, like this:

 

Syntax: my_dict = dict([(key1, value1), (key2, value2), (key3, value3)])

Example:

05
3. Using dictionary comprehension:

Another method of creating a dictionary in Python is by using dictionary comprehension, which is a concise way to create a dictionary from an iterable, such as a list or a tuple. The syntax for dictionary comprehension is as follows:

Syntax: {key_expression: value_expression for item in iterable}

For example:

06

In this example, we created a dictionary ‘my_dict’ that maps each name in the ‘names’ list to its corresponding age in the ‘ages’ list, using dictionary comprehension.

 

Using dictionary comprehension can be a convenient way to create dictionaries in Python, especially when you want to generate them dynamically based on certain conditions or operations performed on other data structures.

Accessing the Elements in a Dictionary

Accessing elements in a dictionary is done by using the keys. The keys of a dictionary should be unique and immutable. 

Here are some ways to access the elements of a dictionary in Python:

 

1. Using square bracket notation:

Square bracket notation is a very common and straightforward way of accessing values in a dictionary. To access a specific value in a dictionary, you simply need to specify the key associated with that value inside a pair of square brackets.

Syntax: my_dict[key]

This will return the value associated with the given key.

For example:

07

In this example, we have a dictionary named ‘my_dict’ which contains three key-value pairs. To access the value associated with the key ‘apple’, we use the square bracket notation with the key inside the brackets. This will return the value 2, which is then printed to the console similarly we can access the other values as well.

 

Remember, dictionaries are mutable, so you can update the value of a key using the square bracket notation as well.

 

Note:

It’s important to note that if you try to access a key that does not exist in the dictionary using square bracket notation, you will get a KeyError. So, it’s always a good idea to check if a key exists in the dictionary before accessing it using this method.

 

2. Using the get() method:

The get() method is a built-in method in Python dictionaries that allows you to access the value of a specific key in the dictionary. This method takes two arguments: the key you want to retrieve the value for, and an optional default value to return if the key does not exist in the dictionary.

 

The syntax for the get() method is as follows:

 

Syntax: my_dict.get(key, default_value)

 

Here, ‘my_dict’ is the dictionary you want to retrieve a value from, ‘key’ is the key for which you want to retrieve the value, and ‘default_value’ is an optional parameter that specifies the value to return if the key does not exist in the dictionary.

 

For example, let’s say you have a dictionary that stores the prices of various items:

prices = {‘apple’: 0.50, ‘banana’: 0.25, ‘orange’: 0.75}

 

You can use the get() method to retrieve the price of an item like this:

08

This will return the value 0.50, which is the price of an apple.


If you try to retrieve the value for a key that does not exist in the dictionary, the get() method will return None by default. For example:

09

This will return None, since there is no key called ‘pear’ in the prices dictionary.


However, you can specify a default value to return instead of None by passing it as the second argument to the get() method. For example:

10

This will return 1.00, since the key ‘pear’ does not exist in the prices dictionary, and we specified 1.00 as the default value to return.

 

3. Using the keys() method:

The keys() method in Python returns a view object that contains all the keys of a dictionary. This method is particularly useful when you need to iterate over the keys of a dictionary, or if you need a list of all the keys in the dictionary.

 

The syntax for using the keys() method in Python is:

 

Syntax: my_dict.keys()

 

Here, my_dict is the dictionary for which you want to retrieve the keys. The keys() method returns a view object that contains all the keys of the dictionary.

 

View Object: 

A view object is a dynamic object that provides a view into the original dictionary. This means that changes made to the dictionary are reflected in the view object, and vice versa. The view object does not create a copy of the dictionary, but rather provides a live representation of the dictionary’s contents. You can use a view object to access, iterate over, and perform operations on the keys or values of a dictionary without actually modifying the original dictionary.

 

Here’s an example of how to use key() method to access the keys in a dictionary:

11

In this example, we create a dictionary called my_dict and then use the keys() method to get a view object of all the keys in the dictionary. We then use a for loop to iterate over the keys and print each key.


Note that the keys() method returns a view object, not a list of keys. However, you can convert the view object into a list using the list() method if you need to.

12

This will convert the view object returned by the keys() method into a list and print it.

 

4. Using the values() method:

Just like the key method, values() method in Python’s dictionary data type returns a view object that contains all the values of the dictionary. The view object is iterable, which means you can loop through it and access the individual values.

 

Syntax: my_dict.values()

 

Here is an example on how to use values() method in python:

13

In this example, the values() method is called on my_dict dictionary and it returns a view object containing all the values (3, 5, 2). We store this view object in the variable values.

 

We also use list() constructor and for loop to access the values out of view object format.

Note that like the keys() method, the values() method also returns a dynamic view object that reflects any changes made to the dictionary. So, if you modify the values of the dictionary, the view object returned by values() method will also reflect the updated values.

 

5. Using item() method

Until now we have discussed about how we can access the keys or the values separately using the keys() method and values() method, now let’s mix things up a bit, we know that an item is a pair of key and value in a dictionary. The items() method is a method that returns a view object that contains the key-value pairs of a dictionary. This view object is essentially a set-like object that provides a dynamic view on the dictionary’s entries.

 

Using the items() method, you can iterate over the items of the dictionary, where each item is a tuple containing the key and its corresponding value. This can be useful when you need to access both the key and value of a dictionary item simultaneously.

 

The syntax for using the items() method is very similar to the syntax for using the keys() and values() methods. You simply call the items() method on the dictionary object:

 

Syntax:

my_dict.items()

 

Here is an example of how you can use item() method on a dictionary to access the items.

14

In the above example we used the items() method to create a view object of the dictionary and we used the list() and tuple() constructor to change its data type to access them.


we can also iterate over this view object using a for loop to access each key-value pair:

15-4

Note that like the keys() and values() methods, the items() method returns a dynamic view object that reflects any changes made to the dictionary. So, if you add, remove, or modify an item in the dictionary, the view object will be automatically updated to reflect the changes.

Updating and Adding New Elements in a Dictionary

One of the most useful features of dictionaries is their ability to dynamically add, update, and remove elements. This means that you can modify the contents of a dictionary as your program runs, allowing you to create more powerful and flexible data structures. In this section, we’ll explore the methods for adding and removing elements from a dictionary.

 

1. Using square bracket notation

Adding a new key-value pair to a dictionary is a common operation in Python programming. This can be done using the square bracket notation. To add a new key-value pair, you simply need to specify the key inside the square brackets and assign a value to it. If the key already exists in the dictionary, the value associated with that key will be updated to the new value. If the key does not exist, a new key-value pair will be added to the dictionary.

Here’s an example:

16

In the example above, we first create a dictionary called my_dict with three key-value pairs. We then add a new key-value pair to the dictionary using the square bracket notation. The key is ‘grape’ and the value is 4. When we print the dictionary, we can see that the new key-value pair has been added to the dictionary.


Note that if the key already exists in the dictionary, its value will be updated to the new value. For example, if we add the key ‘banana’ with a value of 5 using the square bracket notation, the value associated with the key ‘orange’ will be updated to 5 in the dictionary.

17
2. Using setdefault() method:

Python’s dict class comes with a handy method called setdefault() that can be used to add a new key-value pair to a dictionary. This method works similarly to accessing dictionary elements using square bracket notation, but with an added feature of setting a default value for a new key.

 

The setdefault() method takes two arguments: the key that you want to add, and a default value that will be assigned to the key if it doesn’t already exist in the dictionary. The method then returns the value of the key in the dictionary.

 

Here’s the syntax for using the setdefault() method:

 

Syntax: 

my_dict.setdefault(key, default_value)

  • my_dict: the dictionary to which we want to add the new elements to.
  • key: the name of the key we want to add to the dictionary.
  • default_value: the default value for the key, if the key does not already exist.

 

If the key is not already present in the dictionary, setdefault() will add it with the specified default value and return the default value. If the key is already present, the method will return the value associated with the key without modifying the dictionary.

 

Let’s look at an example to see how this works:

18

In this example, we create an empty dictionary and add a new key-value pair using setdefault(). We then add another key-value pair, and finally try to update the value of an existing key. As you can see, setdefault() only updates the dictionary if the key does not exist in the dictionary.

 

Using the setdefault() method can be useful when you want to add a default value for a new key, without having to check if the key already exists in the dictionary. It saves you from writing extra code and makes your code more concise.

 

3. Using update() method:

Another way of adding elements or updating a dictionary is by using the update() method.

 

This method takes a dictionary as an argument and adds all the key-value pairs from the given dictionary to the original dictionary.

 

The syntax for using the update() method is as follows:

 

Syntax: 

my_dict.update(new_dict)

 

Here, my_dict is the original dictionary to which you want to add the key-value pairs, and new_dict is the dictionary that contains the key-value pairs you want to add.

 

If the key already exists in my_dict, then the corresponding value in my_dict will be updated with the value from new_dict. If the key does not exist in my_dict, then a new key-value pair will be added to the dictionary.

 

Example:

Let’s say you have a dictionary fruits that contains the following key-value pairs:

fruits = {‘apple’: 3, ‘banana’: 5, ‘orange’: 2}

 

Now, let’s say you want to add the following key-value pairs to the fruits dictionary:

new_fruits = {‘pear’: 4, ‘grape’: 7}

 

You can use the update() method to add these key-value pairs to the fruits dictionary as follows:

19

The update() method is a useful way to add new key-value pairs to a dictionary. It can be especially handy when you want to merge two dictionaries together. Keep in mind that if the key already exists in the original dictionary, the value will be updated with the new value.

Dictionary Operations in Python:

Now that we have looked at how we can add new elements to the dictionary, let us take a look at some of the most common dictionary operations that will come in handy when you are working with dictionary datatypes in python.

 

Dictionary operations refer to the various actions or manipulations that can be performed on a dictionary to retrieve or modify its contents. These operations can be useful in a wide range of applications, from simple data processing to complex programming tasks. In this section, we will take a look at some of the most common dictionary operations that you can use to work with your dictionaries.

 

1. Merging Dictionaries

Merging dictionaries is a common operation that is often required in Python programming.

 

One way to merge two dictionaries is to use the update() method. The update() method can take one or more dictionaries as arguments, and it adds all the key-value pairs from the given dictionaries to the original dictionary. If a key is present in both dictionaries, the value from the second dictionary will overwrite the value in the original dictionary.

However, since we have already discussed the update() method in depth in the previous section, let’s take a look at different method to merge two dictionaries.

 
Unpacking Operator

Another way to merge dictionaries is to use the unpacking operator (**). This method is only available in Python 3.5 and later versions. The unpacking operator can be used to merge two or more dictionaries into a single dictionary. If a key is present in both dictionaries, the value from the second dictionary will overwrite the value in the first dictionary.

 

Here’s an example of how to merge two dictionaries using the unpacking operator:

20

In this example, the key ‘b’ is present in both dictionaries. The value for ‘b’ in dict2 overwrites the value for ‘b’ in dict1.

 

Both methods of merging dictionaries have their advantages and disadvantages. The update() method is more versatile and can merge multiple dictionaries at once, while the unpacking operator is more concise and readable.

 

2. Removing Elements from a Dictionary:

In addition to adding elements to a dictionary, you may also need to remove elements from it. In Python, you can remove elements from a dictionary using various methods.

Let’s take a look at a few of them:

 

Using ‘del’ Keyword

You can use the del keyword to remove an element from a dictionary. The del keyword takes the key as an argument and removes the key-value pair associated with that key from the dictionary. 

 

The syntax for using the del keyword is:

 del my_dict[key]

 

Here’s an example:

21

Note that if you try to delete a key that does not exist in the dictionary, it will raise a KeyError. You can use the ‘in’ keyword to check if a key exists in the dictionary before deleting it, like this:

22

And thus, avoiding any errors.

 
Using the pop() method:

Using the pop() method is another way to remove an element from a dictionary. The pop() method takes a key as an argument and removes the corresponding key-value pair from the dictionary. If the key is not present in the dictionary, then a KeyError is raised. You can also provide a default value to be returned in case the key is not present in the dictionary. The syntax for using the pop() method is: 

 

Syntax: my_dict.pop(key, default_value)

 

When you use the pop() method to remove an element from the dictionary, you can also store the value associated with the key in a variable, if required. This way, you can use the value after removing the key-value pair from the dictionary.

 

Here’s an example of using the pop() method to remove an element from a dictionary:

23

In this example, we have used the pop() method to remove the key-value pair with key ‘banana’ from the dictionary. The value associated with this key (i.e., 3) has been stored in the variable ‘value’. Finally, we have printed the updated dictionary and the value that was removed.

 
Using the popitem() method:

The popitem() method is used to remove and return the last key-value pair from the dictionary as a tuple. This method is useful when you want to remove a random key-value pair from the dictionary, as dictionaries in Python are unordered.

 

The syntax for using the popitem() method is:

Syntax: my_dict.popitem()

 

This method does not take any arguments.

When the popitem() method is called on a dictionary, it removes the last inserted key-value pair and returns it as a tuple. If the dictionary is empty, calling the popitem() method will throw a KeyError.

 

Here is an example of how to use the popitem() method:

24

In this example, we call the popitem() method on the dictionary my_dict. The last inserted key-value pair (‘orange’, 3) is removed and returned as a tuple. We then print the removed key-value pair, which outputs ‘orange’ 3, and the updated dictionary, which outputs {‘apple’: 2, ‘banana’: 4}.

3. Membership Testing in a Dictionary:

Membership testing is a common operation in Python that allows you to check if a particular key or value is present in a dictionary. There are two ways to perform membership testing in a dictionary:

 

Using the ‘in’ Keyword

You can check if a key is present in a dictionary using the in keyword. The ‘in’ keyword returns True if the key is present in the dictionary, and False otherwise.

 

Here’s an example:

25

In the above example, the first print statement checks if the key ‘apple’ is present in the my_dict dictionary, and it returns True since the key is present. The second print statement checks if the key ‘grape’ is present in the my_dict dictionary, and it returns False since the key is not present.


To check if a value is present in a dictionary, you can use the in keyword followed by the .values() method of the dictionary and the value you want to check. For example:

26

In the above example, we found weather a particular value is present in a dictionary or not.

4. Length of a Dictionary:

The length of a dictionary gives the total number of key value pairs or items that are present in a dictionary.

 

The length of a dictionary can be determined using the len() function. The len() function returns the number of key-value pairs in the dictionary. The syntax for using the len() function is:

 

len(my_dict)

For example, consider the following dictionary:

my_dict = {‘apple’: 2, ‘banana’: 5, ‘orange’: 1, ‘grape’: 10}

To find the length of this dictionary, we can use the len() function as follows:

27

The output indicates that the dictionary contains 4 key-value pairs.

 

5. Sorting a Dictionary:

Imagine you have a dictionary with a huge number of elements that are randomly ordered. You need to display these elements in a specific order, but the thought of manually rearranging the elements can make your head spin. This is where sorting a dictionary comes in handy. By sorting the elements of the dictionary, you can quickly and easily organize the data in the order that you need it to be displayed. Not only does this make the data more readable, but it also helps to prevent confusion and errors that can arise from having unordered data. So, let’s dive into the different ways you can sort a dictionary in Python!

 

Sorting a dictionary can be done in different ways based on the requirement. Here are the three common ways to sort a dictionary:

 

  1. Sorting by keys:

    The sorted() function can be used to sort a dictionary by its keys. It returns a list of sorted keys, and you can use it to iterate over the dictionary in a sorted order.

 

         2. Sorting by values: To sort a dictionary by its values, you can use the sorted() function along with the key argument. The key argument should be a function that takes one argument (the dictionary key) and returns the value to be used for sorting.

 

In all the above methods, the original dictionary is not changed. Instead, a new sorted list or dictionary is returned, which can be used further as per the requirement.

 

1. Sorting by keys:

Sorting by keys is a common way to organize the contents of a dictionary. This method involves sorting the keys of the dictionary in ascending or descending order and then creating a new dictionary with the sorted keys and their corresponding values. Sorting by keys can help make the dictionary more readable and easier to navigate, especially when dealing with large amounts of data. It can also be useful when we want to retrieve specific elements based on their key values. In Python, we can sort a dictionary by keys using the sorted() function.

 

Syntax: sorted_dict = dict(sorted(my_dict.items()))

Example:
28

Here we can see that the dictionary has been sorted in the alphabetical order of their keys.

 
2. Sorting by values:

Sorting by values is another way to sort a dictionary. In this case, the elements are sorted based on their values instead of keys. This can be useful when we want to retrieve the elements based on their values.

 

To sort a dictionary by values, we can use the sorted() function along with a lambda function that specifies the value to be used for sorting.

 

The syntax for sorting a dictionary by values is as follows:

sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))

 

  • sorted(): A built-in function in Python that returns a new sorted list from the items in the iterable (in this case, the items in the dictionary).
  • my_dict.items(): A method that returns a view object that contains the key-value pairs of the dictionary as a sequence of tuples.
  • key=lambda x: x[1]: A key function that specifies how the items in the dictionary should be sorted. In this case, it sorts the items based on the second element of each tuple (i.e., the values).
 
dict(): 

A constructor that creates a new dictionary from an iterable of key-value pairs (in this case, the sorted list of tuples).

29

In the above example, the dictionary is sorted based on the values of its elements in ascending order.

 

Note: To sort a dictionary in descending order, you can set the reverse parameter to True in the sorted() function like we did with lists and tuples.

 

6. Reversing a Dictionary:

Reversing a dictionary means swapping its keys and values. The original keys become the values and the original values become the keys. This operation can be useful in many situations.

 

To reverse a dictionary, we can use a simple dictionary comprehension. The syntax for reversing a dictionary is:

 

Syntax: reversed_dict = {value: key for key, value in original_dict.items()} 

 

Here, we are iterating over the original_dict using the items() method, which returns a list of key-value pairs. Then, we are creating a new dictionary reversed_dict by swapping the keys and values using a dictionary comprehension.

Note that if the original dictionary has duplicate values, the reversed dictionary will only have one key for each value. This is because a dictionary cannot have duplicate keys.

 

Let’s see an example of how to reverse a dictionary:

30

Conclusion:

In conclusion, dictionaries are a versatile and powerful data structure in Python, and mastering their various operations can greatly enhance your coding skills. We have covered a range of important topics, including adding and removing elements from a dictionary, membership testing, finding the length of a dictionary, sorting by keys, values, and items, as well as reversing a dictionary. By understanding these concepts, you can build more efficient and effective Python programs that manipulate data in meaningful ways.

 

Whether you’re a beginner or an experienced Python developer, there’s always something new to learn about dictionaries. So, keep practicing and exploring this topic, and don’t hesitate to experiment with different approaches and techniques. Tank you for reading and visit 1stepgrow

Christmas & New Year Offer

30% Off

On All Our Courses:)

Enroll Now and Get Future Ready!!