×

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

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

Python IDE names

Python is one of the most renowned programming languages. It has different execution conditions and a great many compilers to execute the python programs, e.g., PyCharm, PyDev, Jupyter Notebook, Visual...

6 minutes read.

Python all() Function

Python all() Function The all() function in Python returns a Boolean value ‘True’ if all the items in iterable are true or if the iterable object is empty, else it returns False. Syntax all(iterable) Parameter Iterable: An iterable object...

1 minute read.

Python bool()

Python bool() class The bool() class in Python returns the boolean value for the specified object. Syntax class bool([x]) Parameter object: This parameter represents the object, like String, List, Number etc. Return It will always return True, except...

1 minute read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Python Interface

When creating an application, it is important to continuously keep track of its changes. As an application grows, sometimes it gets hard to manage its updates and changes. Often, you...

4 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

Python property()

Python property() class The property() class in Python returns a property attribute. Syntax class property(fget=None, fset=None, fdel=None, doc=None) Parameter fget: This attribute is used for getting an attribute value. fset : This parameter sets an attribute value. fdel: It is a function for deleting...

1 minute read.