11 Most Useful Python Dictionary Methods with Examples

11 Most Useful Python Dictionary Methods: In this tutorial, we will learn about the Python dictionary methods which are used for various dictionary operations such as insert, remove, get, update, etc. Learn these methods with the help of examples. By IncludeHelp Last updated : June 10, 2023

A Python dictionary is a mapping between a set of indices (keys) and a set of values. It is an extremely useful data storage construct where each element is accessed by a unique key.

The following are the Python dictionary methods that you can use for the various dictionary operations.

1. clear() Method

The clear() method is used to remove all elements from the dictionary.

Syntax

dictionary_name.clear( )

Example

# Python Dictionary clear() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "per" : 98.5
}

# printing dictionary
print("data before clearing...")
print(student)

# clearing dictionary
student.clear()

# printing dictionary after clear()
print("data after clearing...")
print(student)

Output

data before clearing...
{'course': 'B.Tech', 'roll_no': 101, 'per': 98.5, 'name': 'Shivang'}
data after clearing...
{}

2. copy() Method

The copy() method is used to copy a dictionary, it returns a shallow copy of this dictionary.

Syntax

dictionary_name.copy()

Example

# Python Dictionary copy() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "per" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# copying dictionary
student_x = student.copy()

# printing dictionary
print("data of student_x dictionary...")
print(student_x)

Output

data of student dictionary...
{'roll_no': 101, 'course': 'B.Tech', 'name': 'Shivang', 'per': 98.5}
data of student_x dictionary...
{'roll_no': 101, 'course': 'B.Tech', 'name': 'Shivang', 'per': 98.5}

3. fromkeys() Method

The fromkeys() method is used to create a dictionary with given keys and value.

Syntax

dictionary_name.fromkeys(keys, value)

Example

# Python Dictionary fromkeys() Method with Example

# keys iterbale
keys = ('id', 'age', 'perc')

# value
value = 0

# creating dictionary with keys and value
x = dict.fromkeys(keys, value)

# printing dictionary
print("data of x dictionary...")
print(x)

# creating dictionary with keys only
y = dict.fromkeys(keys)

# printing dictionary
print("data of y dictionary...")
print(y)

Output

data of x dictionary...
{'perc': 0, 'id': 0, 'age': 0}
data of y dictionary...
{'perc': None, 'id': None, 'age': None}

4. get() Method

The get() method is used to get the value of an element based on the specified key.

Syntax

dictionary_name.get(key)

Example

# Python Dictionary get() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# printing the value of "roll_no"
print("roll_no is:", student.get('roll_no'))

# printing the value of "name"
print("name is:", student.get('name'))

# printing the value of "course"
print("course is:", student.get('course'))

# printing the value of "perc"
print("perc is:", student.get('perc'))

# trying to get item of the key which does not exist
print("address is:", student.get('address'))

# trying to get item of the key which does not exist
# and returning some value if key does not exist
print("address is:", student.get('address', "does not exist."))

Output

data of student dictionary...
{'perc': 98.5, 'course': 'B.Tech', 'name': 'Shivang', 'roll_no': 101}
roll_no is: 101
name is: Shivang
course is: B.Tech
perc is: 98.5
address is: None
address is: does not exist.

5. items() Method

The items() method is used to get the all items as a view object, the view object represents the key-value pair of the dictionary.

Syntax

dictionary_name.items()

Example

# Python Dictionary items() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# printing items
print("items of student dictionary...")
print(student.items())

# printing return type of student.items() Method
print("return type is: ", type(student.items()))

Output

data of student dictionary...
{'name': 'Shivang', 'perc': 98.5, 'roll_no': 101, 'course': 'B.Tech'}
items of student dictionary...
dict_items([('name', 'Shivang'), ('perc', 98.5), ('roll_no', 101), ('course', 'B.Tech')])
return type is:  <class 'dict_items'>

6. keys() Method

The keys() method is used to get the all keys as a view object, this view object contains all keys of the dictionary.

Syntax

dictionary_name.keys()

Example

# Python Dictionary keys() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# printing keys
print("keys of student dictionary...")
print(student.keys())

# printing return type of student.keys() Method
print("return type is: ", type(student.keys()))

Output

data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
keys of student dictionary...
dict_keys(['course', 'roll_no', 'perc', 'name'])
return type is:  <class 'dict_keys'>

7. pop() Method

The pop() method is used to remove an item from the dictionary with specified key from the dictionary.

Syntax

dictionary_name.pop(key, default_value)

Example

# Python Dictionary pop() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# removing 'roll_no'
x = student.pop('roll_no')
print(x, ' is removed.')

# removing 'name'
x = student.pop('name')
print(x, ' is removed.')

# removing 'course'
x = student.pop('course')
print(x, ' is removed.')

# removing 'perc'
x = student.pop('perc')
print(x, ' is removed.')

# printing default value if key does 
# not exist
x = student.pop('address', 'address does not exist.')
print(x)

Output

data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
101  is removed.
Shivang  is removed.
B.Tech  is removed.
98.5  is removed.
address does not exist.

8. popitem() Method

The popitem() method is used to remove random/last inserted item from the dictionary.

Syntax

dictionary_name.popitem()

Example

# Python Dictionary popitem() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# removing item
x = student.popitem()
print(x, ' is removed.')

# removing item
x = student.popitem()
print(x, ' is removed.')

Output (On Python version 3)

data of student dictionary...
{'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'roll_no': 101}
('name', 'Shivang')  is removed.
('course', 'B.Tech')  is removed.

Output (On Python version 3.7.4)

data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
('perc', 98.5)  is removed.
('course', 'B.Tech')  is removed.

9. setdefault() Method

The setdefault() method is used to get the value of an item with the specified key and it sets an item (key, value) if the specified key does not exist in the dictionary.

Syntax

dictionary_name.setdefault(key, value)

Example

# Python Dictionary setdefault() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# getting value of 'roll_no'
x = student.setdefault('roll_no', 0)
print('roll_no: ', x)

# getting value of address key
# that does not exist, then function
# inserts given key & value
x = student.setdefault('address', 'New Delhi')
print('address: ', x)

# printing dictionary
print("data of student dictionary after setdefault()...")
print(student)

# getting value of age key
# that does not exist, then function
# inserts given key & None
x = student.setdefault('age')
print('age: ', x)

# printing dictionary
print("data of student dictionary after setdefault()...")
print(student)

Output

data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
roll_no:  101
address:  New Delhi
data of student dictionary after setdefault()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'address': 'New Delhi'}
age:  None
data of student dictionary after setdefault()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'address': 'New Delhi', 'age': None}

10. update() Method

We can join two dictionaries into one or two dictionaries can be merged into one by using the update() method. The update() merges the keys and values of one dictionary into the other.

It overwrites the value if, both the dictionaries contains the same key.

Syntax

dictionary_name_1.update(dictionary_name_2)

Example

# Python Dictionary update() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# inserting an item
student.update({'city' : 'Indore'})

# printing dictionary after update()
print("data of student dictionary after update()...")
print(student)

# inserting multiple items
student.update({'city' : 'Indore', 'address' : 'Tech park'})

# printing dictionary after update()
print("data of student dictionary after update()...")
print(student)

Output

data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
data of student dictionary after update()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'city': 'Indore'}
data of student dictionary after update()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'city': 'Indore', 'address': 'Tech park'}

11. values() Method

The values() method is used to get all values of a dictionary, it returns a view object that contains the all values of the dictionary as a list.

Syntax

dictionary_name.values()

Example

# Python Dictionary values() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# getting all values
x = student.values()
print(x)

# printing type of values() Method
print('Type is: ',type(student.values()))

# changing the value
# it will effect the value of view object also
student['course'] = 'MCA'

# printing dictionary
print("data of student dictionary...")
print(student)

# getting all values
x = student.values()
print(x)

Output

data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
dict_values([101, 'Shivang', 'B.Tech', 98.5])
Type is:  <class 'dict_values'>
data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'MCA', 'perc': 98.5}
dict_values([101, 'Shivang', 'MCA', 98.5])

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.