×

Python Dictionary Methods

Python Dictionary Methods

Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow:

Methods Description
clear() The dictionary.clear() method removes all the elements from the dictionary.
copy() The dictionary.copy() method returns a copy of the specified Dictionary.
fromkeys() The dictionary.fromkeys() method returns a dictionary with the specified keys and values.
get() This method returns the value for the given key.
items() The dictionary.items() method returns a list containing a tuple for each key value pair
keys() This method returns View Object of All Keys
pop() The dictionary.pop() method removes and returns element having the specified key.
popitem() This method removes the last inserted key-value pair
setdefault() The dictionary.setdefault() method inserts Key with a Value if Key is not Present and returns the value of the specified key
update() The dictionary.update()updates the dictionary with the specified key-value pairs
values() This method returns a list of all the values in the dictionary

Example 1

 # Python program explaining
 # the dictionary methods
 # initialising the dictionary
 fruits = {
  "banana" : "apple",
   "orange": "mango",
   "grapes": 5
 }
 # printing the Dictionary
 print("Dictionary:",fruits)
 # the setdefault() method
 # returning the value of the key.
 print("The setdefault() method..")
 defaultValue=fruits.setdefault("grapes","vitamin c")
 print("\nValue of the key: \n", defaultValue)
 # the popitem() method
 # pop the last element
 fruits.popitem()
 print("\nAfter poping the last item..")
 print('Remaining dictionary: ', fruits)
 # the pop() method
 # removing the "banana" element from the dictionary.
 leftFruit=fruits.pop("banana")
 print("\nMy final lists of fruits are\n", fruits) 

Output

 Dictionary: {'orange': 'mango', 'banana': 'apple', 'grapes': 5}
 The setdefault() method..
 Value of the key: 
  5
 After poping the last item..
 Remaining dictionary:  {'banana': 'apple', 'grapes': 5}
 My final lists of fruits are
  {'grapes': 5} 

Example 2

 # Python program explaining
 # the dictionary methods
 # initializing the student dictionary
 student = {'studentName': 'Reema','Roll No':'15cs1029'}
 print("The actual Student Details:",student)
 # initializing the second dicitonary with updated values
 updatedStudent= {'studentName': 'Reema','Roll No':'15ME1028','age':22}
 # the dictionary.update() method
 # update the value of key 'Roll' 
 student.update(updatedStudent) 
 print("Student details after updation:") 
 print(student)
 # the dictionary.get() method
 # will return the key value of name and language
 print('Student Name: ', student.get('studentName'))
 print('Roll No: ', student.get('Roll No'))
 # the dictionary.items() method
 # returns a view object that displays a list of a given dictionary's tuple pair
 items = student.items()
 print('Original week list:', items) 

Output

 The actual Student Details: {'studentName': 'Reema', 'Roll No': '15cs1029'}
 Student details after updation:
 {'age': 22, 'studentName': 'Reema', 'Roll No': '15ME1028'}
 Student Name:  Reema
 Roll No:  15ME1028
 Original week list: dict_items([('age', 22), ('studentName', 'Reema'), ('Roll No', '15ME1028')]) 

Example 3

 # Python program explaining
 # the dictionary methods
 # initializing the week dictionary
 week = { 'Monday': 1, 'Tuesday': 2, 'wednesday': 3 ,'Thursday':4,'Friday':5}
 print("Actual dictionary:",week)
 # the dictionary.keys() method
 # Returning a list containing the dictionary's keys
 items = week.keys()
 print('Original week list:', items)
 # the dictionary.copy() method
 # copying the elements of dictionary in dictionary1
 dictionary1 = week.copy()
 print("After copying the dictionary elements in dictionary1...")
 print('dictionary1: ', dictionary1) 
 # the dictionary.clear() method
 # clearing all the elements
 week.clear()
 print('Removing all the element using clear()')
 print('Week List : ', week)
 print('dictionary1: ', dictionary1) 

Output

 Actual dictionary: {'wednesday': 3, 'Friday': 5, 'Tuesday': 2, 'Thursday': 4, 'Monday': 1}
 Original week list: dict_keys(['wednesday', 'Friday', 'Tuesday', 'Thursday', 'Monday'])
 After copying the dictionary elements in dictionary1...
 dictionary1:  {'wednesday': 3, 'Friday': 5, 'Tuesday': 2, 'Thursday': 4, 'Monday': 1}
 Removing all the element using clear()
 Week List :  {}
 dictionary1:  {'wednesday': 3, 'Friday': 5, 'Tuesday': 2, 'Thursday': 4, 'Monday': 1} 

Related Topics

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

The Calendar Module of Python

The calendar module provides calendar features, including printing functions for a specific month or year. Default is the first day of the week on Monday and the last day on Sunday...

3 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

3 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Python Dictionary get() method

Python Dictionary get() method The dictionary.get() method returns the value of the item with the specified key. Syntax dictionary.get(keyname, value) Parameter keyname- This parameter represents the key to be searched in the dictionary. value- The parameter...

1 minute read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.