Loading...

Dictionary methods in Python

Dictionary methods in Python

Hey readers, in this article we are going to discuss the dictionary methods. If you are not aware of dictionaries, do not worry. We will also discuss why we use dictionaries, how to create them, and some of the important and frequently used in-built dictionary methods. Let us get started without any delay.

Introduction

Python has a variety of data types. They are string(text such as “codedamn”, “python”, etc), integers(whole numbers such as 2,32, etc), floats(integers such as 0.4, 53.6, etc), boolean(either True or False), lists(multiple elements enclosed in square brackets such as [2, “hello”, 59.4], etc), tuples(multiple elements enclosed in round brackets such as(92, “hello”, 59.4), etc) and dictionaries. So dictionaries are one of the datatypes in python.

What are dictionaries in python?

As discussed above, dictionaries are one of the datatypes in python. It contains key value pairs enclosed within the curly brackets( {} ). They are mutable and ordered. The key and its corresponding value are separated by a colon, and each key-value pair in a dictionary of python are separated by a comma( , ). There can be multiple keys with the same values but there can’t be the same key with multiple different values.

By now, it might have been quite clear that the dictionary in python should contain unique key-value pairs. It can contain a list, a tuple, or a dictionary inside it. The dictionaries in python are case-sensitive. Even a slight change as minor as a change in the case will be considered different. The key-value pairs of a dictionary are unordered. So there is no chance for us to access them using their index. A typical dictionary looks as shown below.

details = {"name": "John", "age": 34, "place": "London"} print(details)
Code language: Python (python)

The output you will get is shown below.

{'name': 'John', 'age': 34, 'place': 'London'}
Code language: Bash (bash)

Why use dictionaries?

Keys in dictionaries are similar to variables. As you know, variables in python are containers that can store data of different datatypes i.e values. We can declare an infinite number of variables in python. Why do you think they are placed inside curly brackets and made a new datatype named dictionary? In a dictionary, we can store the data of all the related topics, unlike a normal variable where all the data gets mixed up. It gets hard for us to look for the data we are searching for.

Let us take an example of a supermarket. What if all the items in a supermarket get mixed up instead of placing related items in one section? It gets very hard for us to search for the things we are looking for, in that case. So the need for a dictionary in python became inevitable. so is the need for us to learn about its usage and methods.

How to create a dictionary?

Using curly brackets

The most simple way to create a dictionary is to put the key-value pairs inside curly brackets where each key and its corresponding value are separated by a colon and each of the pairs in a dictionary is separated by a comma. Below given is a dictionary using the curly brackets.

details = {"name": "John", "age": 34, "place": "London"}
Code language: Python (python)

Using dict()

In this method, we put the keys and their corresponding values inside the round brackets of the dict() constructor. Instead of using a colon between the key and its corresponding value like in the curly brackets method, we use equal to(=) in this method. Below given is a dictionary using dict().

details = dict(name='john', age=43, place='london') print(details)
Code language: Python (python)

The output you will get is shown below.

{'name': 'John', 'age': 34, 'place': 'London'}
Code language: Bash (bash)

In-built methods of a dictionary

As the use of a dictionary in python became a necessity, there are many in-built methods of the dictionary to make working with them easier. We can access keys, access values, delete keys and values, add new key-value pairs, update the value of a key, and many more. Let us discuss some of the important in-built methods of dictionaries which are essential for us to know with examples of each method.

items()

With the help of this method, we can get the key-value pairs from a dictionary in a list. There are no parameters in this method to pass. Each key-value pair in the list that is returned will be a tuple i.e inside round brackets. Given below is an example of this method.

details = {"name": "John", "age": 34, "place": "London"} list = details.items() print(list)
Code language: Python (python)

The output you will get is shown below.

dict_items([('name', 'John'), ('age', 34), ('place', 'London')])
Code language: Bash (bash)

keys()

If we use the keys() method, we get the keys of a dictionary. We get all the keys enclosed in square brackets separated by commas i.e in the form of a list. The elements of a list are indexed. So we can access the keys which is not possible in the case of a dictionary as it is not ordered. There is no need to pass any parameters in this method. Given below is an example of this method.

details = {"name": "John", "age": 34, "place": "London"} list = details.keys() print(list)
Code language: Python (python)

The output you will get is shown below.

dict_keys(['name', 'age', 'place'])
Code language: Bash (bash)

values()

If we use the values() method, we get the values of a dictionary. We get all the values enclosed in square brackets separated by commas i.e in the form of a list. The elements of a list are indexed. So we can access the values which is not possible in the case of a dictionary as it is not ordered. There is no need to pass any parameters in this method. Given below is an example of this method.

details = {"name": "John", "age": 34, "place": "London"} list = details.values() print(list)
Code language: Python (python)

The output you will get is shown below.

dict_values(['John', 34, 'London'])
Code language: Bash (bash)

get()

We have to pass the key, whose value we want, as a parameter in this method. We can also access the values of the keys of a dictionary without using methods but why do you think there is a need for a separate get() method? It is because by using the get() method we do not have to worry about key errors. Let us understand this method with the help of an example.

details = {"name": "John", "age": 34, "place": "London"} list = details.get('place') print(list)
Code language: Python (python)

The output you will get is shown below.

London
Code language: Bash (bash)

pop()

With the help of this method, we can delete a key-value pair from the dictionary. We have to pass the key of the key-value pair that you want to delete as a parameter. Let us understand this method with the help of an example.

details = {"name": "John", "age": 34, "place": "London"} list = details.pop('place') print(list)
Code language: Python (python)

The output you will get is shown below.

{'name': 'John', 'age': 34}
Code language: Bash (bash)

popitem()

With the help of this method, we can delete the element at the end i.e last key-value pair of a dictionary. There is no need to pass any parameters in this method. There is a possibility of a key error when using this method if the dictionary is empty. It is because this method tries to remove the last element from an empty dictionary, which is not possible. Let us understand this method with the help of an example.

details = {"name": "John", "age": 34, "place": "London"} list = details.popitem() print(details)
Code language: Python (python)

The output you will get is shown below.

{'name': 'John', 'age': 34}
Code language: Bash (bash)

update()

We have to pass key-value pairs enclosed in curly brackets as parameters inside the update() method to add new key-value pairs. If the key we are adding is already present in the dictionary, then the value gets updated. Let us understand this method with the help of an example.

details = {"name": "John", "age": 34, "place": "London"} details.update({"height":178}) print(details)
Code language: Python (python)

The output you will get is shown below.

{'name': 'John', 'age': 34, 'place': 'London', 'height': 178}
Code language: Bash (bash)

fromkeys()

The keys and values of this dictionary are passed as parameters of the fromkeys() method. The first parameter is the sequence of keys and the second parameter is their values. Let us understand this method with the help of an example.

lst = [3, "age"] print(dict.fromkeys(lst,20))
Code language: Python (python)

The output you will get is shown below.

{3: 20, 'age': 20}
Code language: Bash (bash)

copy()

With the help of this method, we can make a copy of an existing dictionary. The new copy copies only elements of the existing ones but not their references. There is no need to pass any parameter inside the copy(). Let us understand this method with the help of an example.

details = {"name": "John", "age": 34, "place": "London"} details1 = details.copy() print(details1)
Code language: PHP (php)

The output you will get is shown below.

{'name': 'John', 'age': 34, 'place': 'London'}
Code language: JavaScript (javascript)

clear()

With the help of this method, we can remove all the elements of a dictionary. There is no need to pass any parameter inside the clear(). Let us understand this method with the help of an example.

details = {"name": "John", "age": 34, "place": "London"} details.clear() print(details)
Code language: Python (python)

The output you will get is shown below.

{}
Code language: Bash (bash)

Conclusion

In this article, we have discussed dictionaries in python, why we use dictionaries, how to create them, and some of the important and frequently used in-built dictionary methods. Do check out the python course at codedamn to continue your python learning. Codedamn has inbuilt playgrounds where you can code. So there is no need to arrange a special environment for your device. You can easily start coding in the codedamn website itself. Do join our community. All of your doubts can instantly be solved. Projects are very important for your coding career. There are a lot of projects at codedamn, from which you can choose and start working.

Frequently Asked Questions- FAQ

What are dictionaries in python?

Dictionaries are one of the datatypes in python. It contains key value pairs enclosed within the curly brackets({}).

Why items() method is used?

To get the elements of a dictionary enclosed in square brackets and separated by commas. Each key-value pair in the list that is returned will be a tuple i.e inside round brackets.

Why the keys() method is used?

We get all the keys enclosed in square brackets separated by commas i.e in the form of a list. So we can access the keys which is not possible in the case of a dictionary as it is not ordered.

Why values() method is used?

To get all the values of the dictionary in a list. So we can access the values which is not possible in the case of a dictionary as it is not ordered.

Why pop() method is used?

We use this method to remove an element.

Why popitem() method is used?

With the help of this method, we can delete the element at the end i.e last key-value pair of a dictionary.

Sharing is caring

Did you like what Manish wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far