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 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.
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:
Â
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.
Â
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.
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.
Â
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.
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”}
In this example, we have a dictionary with three key-value pairs.Â
Â
The keys are:
Â
And the values are:
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 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.
Â
{key1:value1, key2:value2, key3:value3, …}
{item1, item2, item3, item4, …}
Â
Â
Â
Â
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:
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.
Â
You can create an empty dictionary and add key-value pairs to it later, here is an example:
This approach is useful when you don’t know all the key-value pairs in advance or want to add them dynamically.
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:
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:
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:
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 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:
Â
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:
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.
Â
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.
Â
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:
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:
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:
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.
Â
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.
Â
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:
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.
This will convert the view object returned by the keys() method into a list and print it.
Â
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:
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.
Â
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:
Â
my_dict.items()
Â
Here is an example of how you can use item() method on a dictionary to access the items.
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:
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.
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.
Â
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:
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.
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:
Â
my_dict.setdefault(key, default_value)
Â
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:
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.
Â
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:
Â
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.
Â
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:
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.
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.
Â
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.
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:
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.
Â
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:
Â
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:
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:
And thus, avoiding any errors.
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:
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.
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:
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}.
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:
Â
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:
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:
In the above example, we found weather a particular value is present in a dictionary or not.
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:
The output indicates that the dictionary contains 4 key-value pairs.
Â
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:
Â
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()))
Here we can see that the dictionary has been sorted in the alphabetical order of their keys.
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]))
Â
A constructor that creates a new dictionary from an iterable of key-value pairs (in this case, the sorted list of tuples).
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.
Â
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:
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
We provide online certification in Data Science and AI, Digital Marketing, Data Analytics with a job guarantee program. For more information, contact us today!
Courses
1stepGrow
Anaconda | Jupyter Notebook | Git & GitHub (Version Control Systems) | Python Programming Language | R Programming Langauage | Linear Algebra & Statistics | ANOVA | Hypothesis Testing | Machine Learning | Data Cleaning | Data Wrangling | Feature Engineering | Exploratory Data Analytics (EDA) | Â ML Algorithms | Linear Regression | Logistic Regression | Decision Tree | Random Forest | Bagging & Boosting | PCA | SVM | Â Time Series Analysis | Natural Language Processing (NLP) | NLTK | Deep Learning | Neural Networks | Computer Vision | Reinforcement Learning | ANN | CNN | RNN | LSTM | Facebook Prophet | SQL | MongoDB | Advance Excel for Data Science | BI Tools | Tableau | Power BI | Big Data | Hadoop | Apache Spark | Azure Datalake | Cloud Deployment | AWS | GCP | AGILE & SCRUM | Data Science Capstone Projects | ML Capstone Projects | AI Capstone Projects | Domain Training | Business Analytics
WordPress | Elementor | On-Page SEO | Off-Page SEO | Technical SEO | Content SEO | SEM | PPC | Social Media Marketing | Email Marketing | Inbound Marketing | Web Analytics | Facebook Marketing | Mobile App Marketing | Content Marketing | YouTube Marketing | Google My Business (GMB) | CRM | Affiliate Marketing | Influencer Marketing | WordPress Website Development | AI in Digital Marketing | Portfolio Creation for Digital Marketing profile | Digital Marketing Capstone Projects
Jupyter Notebook | Git & GitHub | Python | Linear Algebra & Statistics | ANOVA | Hypothesis Testing | Machine Learning | Data Cleaning | Data Wrangling | Feature Engineering | Exploratory Data Analytics (EDA) | Â ML Algorithms | Linear Regression | Logistic Regression | Decision Tree | Random Forest | Bagging & Boosting | PCA | SVM | Â Time Series Analysis | Natural Language Processing (NLP) | NLTK | SQL | MongoDB | Advance Excel for Data Science | Alteryx | BI Tools | Tableau | Power BI | Big Data | Hadoop | Apache Spark | Azure Datalake | Cloud Deployment | AWS | GCP | AGILE & SCRUM | Data Analytics Capstone Projects
Anjanapura | Arekere | Basavanagudi | Basaveshwara Nagar | Begur | Bellandur | Bommanahalli | Bommasandra | BTM Layout | CV Raman Nagar | Electronic City | Girinagar | Gottigere | Hebbal | Hoodi | HSR Layout | Hulimavu | Indira Nagar | Jalahalli | Jayanagar | J. P. Nagar |Â Kamakshipalya | Kalyan Nagar | Kammanahalli | Kengeri | Koramangala | Kothnur | Krishnarajapuram | Kumaraswamy Layout | Lingarajapuram | Mahadevapura | Mahalakshmi Layout | Malleshwaram | Marathahalli | Mathikere | Nagarbhavi | Nandini Layout | Nayandahalli | Padmanabhanagar | Peenya | Pete Area | Rajaji Nagar | Rajarajeshwari Nagar | Ramamurthy Nagar | R. T. Nagar | Sadashivanagar | Seshadripuram | Shivajinagar | Ulsoor | Uttarahalli | Varthur | Vasanth Nagar | Vidyaranyapura | Vijayanagar | White Field | Yelahanka | Yeshwanthpur
Mumbai | Pune | Nagpur | Delhi | Gurugram | Chennai | Hyderabad | Coimbatore | Bhubaneswar | Kolkata | Indore | Jaipur and More