×

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

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

How to Install Numpy in PyCharm

What is PyCharm? JetBrains created the hybrid platform known as PyCharm as a Python IDE. The Python IDE PyCharm is used by some major companies, including Twitter, Facebook, Amazon, and many...

4 minutes read.

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes 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 List remove() method

Python List remove() method The list.remove () method in Python removes the item at the specified position in the given list. Syntax list.remove(x) Parameter x: This parameter represents the element you want to remove and accepts any type...

1 minute read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

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

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Is Python Object Oriented Programming language

In this tutorial, we will see whether python also belongs to an object-oriented programming language like several others. We will also see the advantages of using OOPs. Further, we will...

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 Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.