Dictionary functions in python with examples || 7 very important Dictionary function

Dictionary functions in python with examples

Dictionary functions in python with examples

There are various types of Dictionary functions in python with examples dictionary.

#1 len()

Dictionary functions in python len() is used to find length of dictionary.

d = { ‘Name’ : ‘Deepak’, ‘city’ : ‘Indore’, ‘Hobby’ : ‘Cricket’ }

print( len(d) )

Output

3

#2 del()

If we want to delete any element from dictionary we use del() function.

d = { ‘Name’ : ‘Deepak’, ‘city’ : ‘Indore’, ‘Hobby’ : ‘Cricket’ }

del d[ ‘city’ ]

print( d )

Output

{ ‘Name’ : ‘Deepak’, ‘Hobby’ : ‘Cricket’ }

 

#3 sorted

Dictionary functions in python sorted() is used to arrange the dictionary key in sequence. The sorted() function does not affect the original dictionary.

d = { ‘Name’ : ‘Deepak’, ‘city’ : ‘Indore’, ‘Hobby’ : ‘Cricket’ }

print( sorted(d) )

Output

{ ‘city’ : ‘Indore’, ‘Hobby’ : ‘Cricket’, ‘Name’ : ‘Deepak’ }

#4 keys()

keys() function is used to get all keys from dictionary.

d = { ‘Name’ : ‘Deepak’, ‘city’ : ‘Indore’, ‘Hobby’ : ‘Cricket’ }

print( keys(d) )

Output

dict_keys([‘Name’, ‘city’, ‘Hobby’])
 

#5 values()

The values() functions return the list of values in the dictionary.

d = { ‘Name’ : ‘Deepak’, ‘city’ : ‘Indore’, ‘Hobby’ : ‘Cricket’ }

print( d.values() )

Output

dict_values([‘Deepak’, ‘Indore’, ‘Cricket’])

#6 items()

The items() functions return the list of key-value pair of dictionary.

d = { ‘Name’ : ‘Deepak’, ‘city’ : ‘Indore’, ‘Hobby’ : ‘Cricket’ }

print( d.items() )

Output

dict_items([(‘Name’, ‘Deepak’), (‘city’, ‘Indore’), (‘Hobby’, ‘Cricket’)])
 

#7 clear()

It is used to delete all elements from dictionary. Hence clear() functional is used to empty the dictionary.

d = { ‘Name’ : ‘Deepak’, ‘city’ : ‘Indore’, ‘Hobby’ : ‘Cricket’ }

d.clear()

print( d )

Output

{}
 

Important Links: Informatics Practices

What is Python Dictionary
How to create Python Dictionary
How to Traverse Dictionary in Python
What is Python List
Characteristics of Python List
How to create Python List
How to Traverse a List in Python
How to Manipulate List in Python
How to Modify multiple elements in Python List
Slicing in Python List
How to delete elements from List in Python

If you like my post please share it with your friends by simply clicking the below social media button, and Don’t forget to comment so we will update ourselves.

[sm-youtube-subscribe]

Share in a Single Click

Leave a Reply

Your email address will not be published. Required fields are marked *