×

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

Io stringio Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

7 minutes read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes 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 Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 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.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Python sorted() function

Python sorted() function The sorted() function returns a sorted list of the specified iterable object. Syntax sorted(iterable, *, key=None, reverse=False) Parameter iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc. key:...

1 minute 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.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 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 Unit Test Cheat String

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.