Python dictionary operations
In this article, we will learn about the python dictionary and dictionary methods.
What is a Python dictionary?
Python Dictionary is key, value paired data structure in python. In general case, we use a dictionary for macking the JSON object or store the key, value paired data in one object. In general, it is unordered collection of key, value paired data.
In Python, we can initialize the dictionary by {}(curly braces) or by simply calling dict() method.
Example,
student = {"Name": "Peter", "Age": "20"}
student = dict(Name="Peter", Age: "20")
How can we access an element from the python dictionary?
Basically, there are two ways to access an element from the python dictionary.
Let’s see an example.
Let’s see an example.
student = {"Name": "Peter", "Age": "20"} print (student['Age']) print (student['DOB']) print (student.get('Name')) print (student.get('DOB', '1/1/2001'))Output, > 20 > KeyError: 'DOB' > Peter > 1/1/2001
As you can see the difference between the two methods. In the first method, if there is no matching element found if throws key error but in the second method if there is no matching element found it gives None or if we want default value we can mention in the second parameter.
How to update the python dictionary?
We can update the python dictionary by the simple update() method. If the key is already available in dictionary it simply updates the dictionary and if the key is not available in the dictionary it will add new key-value paired data. Let’s see the example,
student = {"Name": "Peter", "Age": "20"} student.update(Name="James") print (student) student.update(DOB="1/01/2001") print (student)Output,> {"Name": "James", "Age": "20"} > {"Name": "James", "Age": "20", "DOB": "1/01/2001"}
How to delete the item from python dictionary?
To delete an item from the dictionary we use the pop() method. Let’s see an example.
student = {"Name": "Peter", "Age": "20"} removed_item = student.pop('Age') print (student) print (removed_item)Output,> {"Name": "Peter"} > 20
How to iterate through the python dictionary?
By using python default for loop we can iterate through the python dictionary. Let’s see an example.
student = {"Name": "James", "Age": "20", "DOB": "1/01/2001"} for i in student: print(student[i])Output, > James > 20 > 1/01/2001
Python Dictionary comprehension
Python dictionary comprehension is a very unique and good way to generate the dictionary. It consists of a key, value paired data and for a loop. Lets’s see an example.
dict1= {i:i*2 for i in range(1,5)} print (dict1)Output, {1:1, 2:4, 3:6, 4:8}
This all are a very useful technique in Python Dictionary.
Python dictionary operations
Reviewed by Prashant Suthar
on
September 12, 2019
Rating: 5