Python Dictionary Methods | Dictionary Functions

In this tutorial, we will discuss Python dictionary methods and built-in functions with the help of examples. Python language provides several methods to work with a dictionary.

The list of all dictionary methods are as follows:

  • clear()
  • copy()
  • fromkeys()
  • get()
  • items()
  • keys()
  • values()
  • pop()
  • popitem()
  • setdefault()
  • update()

Let’s understand each dictionary method with syntax and various examples.

Dictionary Methods in Python


1. clear():

This method clears all the elements from the dictionary. The general syntax to call this method is as:

dict.clear()

This method does not take any argument and not return anything.

Example 1:

# Python program to clear a dictionary.
my_dict = {1: "One", 2: "Two", 3: "Three", 4: "Four"}

# Call clear() method to remove all elements from a dictionary.
my_dict.clear()
print(my_dict)
Output:
      {}

2. copy():

This method returns a copy of the dictionary. It creates a shallow copy of a dictionary where every key-value pair is duplicate. The copy() method allows us to modify the dictionary copy without modifying the original dictionary.

The general syntax to declare a copy() method is as:

dict.copy()

In the above syntax, dict is the name of a dictionary. This method does not take any parameter.

Example 2:

# Python program to copy a dictionary.
my_dict = {1: "Apple", 2: "Guava", 3: "Banana", 4: "Orange"}
print("Original dictionary: ")
print(my_dict)

# Call copy() method to create a copy of my_dict().
my_dict2 = my_dict.copy()
print("Copy dictionary: ")
print(my_dict2)

# Modifying the dictionary copy.
my_dict2[2] = "Mango"

# Displaying after modifying.
print("After modifying, original dictionary: ")
print(my_dict)

print("After modifying, Copy dictionary: ")
print(my_dict2)
Output:
      Original dictionary: 
      {1: 'Apple', 2: 'Guava', 3: 'Banana', 4: 'Orange'}
      Copy dictionary: 
      {1: 'Apple', 2: 'Guava', 3: 'Banana', 4: 'Orange'}
      After modifying, original dictionary: 
      {1: 'Apple', 2: 'Guava', 3: 'Banana', 4: 'Orange'}
      After modifying, Copy dictionary: 
      {1: 'Apple', 2: 'Mango', 3: 'Banana', 4: 'Orange'}

In this example, we have created a dictionary of four elements. Then, we have created a copy of the original dictionary using copy() method provided by Python.

This dictionary copy is a new file which does not depend on the original dictionary from which it was produced. Thence, any changes we make to the new dictionary will have no effect at all on the original dictionary.

3. keys():

This method returns a new view or list of dictionary keys. The general syntax to define this method is as below:

dict.keys()

Example 3:

# Python program to get a list of a dictionary keys.
my_dict = {1: "Apple", 2: "Guava", 3: "Banana", 4: "Orange"}

# Calling keys() function to get the keys of dictionary.
dic_keys = my_dict.keys()

print("Dictionary keys: ")
print(dic_keys)
Output:
      Dictionary keys: 
      dict_keys([1, 2, 3, 4])

4. fromkeys():

This method takes a sequence of elements and uses them as keys to construct a fresh dictionary. The basic syntax to define fromkeys() method is as below:

dict.fromkeys(seq[, value])

In the above syntax, dict is the name of a dictionary. This method takes two parameters, as:

  • seq: It represents the list of values for creating keys for the dictionary.
  • value: It represents optional value to be set with each key. If you do not set any value, Python will set “None” by default.

Example 4:

# Python program to create a dictionary by taking a sequence of values as keys.
# Creating a list of keys.
my_keys = [1, 2, 3, 4]

# Calling fromkeys() function to create a dictionary with my_keys and value as "Mahika".
new_dict = dict.fromkeys(my_keys, "Mahika")
print("Dictionary: ", new_dict)
Output:
       Dictionary:  {1: 'Mahika', 2: 'Mahika', 3: 'Mahika', 4: 'Mahika'}

5. get():

This method returns the value of a dictionary keys. It will return None if the key is not present in the dictionary. The general syntax to declare get() method is as:

dict.get(key, default = None)

Example 5:

# Python program to get the value of each dictionary key.
my_dict = {1: "Mahika", 2: "Ivaan", 3: "Mark", 4: "Bob"}

# Call get() method to get the value of first key.
dict_value1 = my_dict.get(1)
print(dict_value1)

# Getting the value of second key.
dict_value2 = my_dict.get(2)
print(dict_value2)
Output:
      Mahika
      Ivaan

6. items():

This method returns a list of key-value pairs in tuple from the dictionary. The basic syntax to define this method is as:

dict.items()

Example 6:

# Python program to get a list of dictionary elements.
my_dict = {1: "Mahika", 2: "Ivaan", 3: "Mark", 4: "Bob"}

# Call items() method to get the dictionary elements in tuple form.
dict = my_dict.items()
print(dict)
Output:
       dict_items([(1, 'Mahika'), (2, 'Ivaan'), (3, 'Mark'), (4, 'Bob')])

7. pop():

This method removes a specific element (or a key: value pair) from a dictionary whose key is specified as its argument. The general syntax to define pop() method is as:

dict.pop(key)

In this syntax, dict is the name of a dictionary. The pop() method takes an argument as key and returns the value of that key.

Example 7:

# Python program to remove a specific element from a dictionary.
my_dict = {1: "Mahika", 2: "Ivaan", 3: "Mark", 4: "Bob"}
print("Original dictionary: ")
print(my_dict)

# Call pop() method to remove an element form a dictionary.
removed_value = my_dict.pop(3)

print("Dictionary after removing an element: ")
print(my_dict)
print("Removed value of key: ", removed_value)
Output:
       Original dictionary: 
       {1: 'Mahika', 2: 'Ivaan', 3: 'Mark', 4: 'Bob'}
       Dictionary after removing an element: 
       {1: 'Mahika', 2: 'Ivaan', 4: 'Bob'}
       Removed value of key:  Mark

8. popitem():

This method removes a random element or key-value pair from a dictionary. The basic form of this method is as:

dict.popitem()

The popitem() method takes no argument and returns an arbitrary key-value pair from the dictionary.

Example 8:

# Python program to remove a random element from a dictionary.
my_dict = {"One": 1, "Two": 2, "Three": 3, "Four": 4}
print("Original dictionary: ")
print(my_dict)

# Call popitem() method to remove a random element form a dictionary.
removed_element = my_dict.popitem()
print("Dictionary after removing a random element: ")
print(my_dict)
print("Removed element: ", removed_element)
Output:
      Original dictionary: 
      {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4}
      Dictionary after removing a random element: 
      {'One': 1, 'Two': 2, 'Three': 3}
      Removed element:  ('Four', 4)

9. setdefault():

This method is used to search for a specified key in a dictionary. It returns the value of the key if found. If not, it returns the specified default value. The basic syntax for using this method is:

dict.setdefault(key, default = None)

Example 9:

# Python program to search am element from a dictionary.
my_dict = {'a': "apple", 'b': "boy", 'c': "cat", 'd': "dog"}

# Call setdefault() method to search an element based on a specified key form a dictionary.
result = my_dict.setdefault('c', None)
print(result)
Output:
      cat

10. update():

This method is used to update a dictionary with a set of key-value pairs from another dictionary. It merges the key-value pairs of one dictionary into another as well as overwrites the values of the other dictionary to the values of the current dictionary if a common key() exists.

The general syntax to declare this method is as:

dict1.update(dict2)

In this syntax, dict1 and dict2 are names of two dictionaries.

Example 10:

# Python program to merge a dictionary into another dictionary.
my_dict1 = {"Name": "Mahika", "Age": 17, "Gender": "Female"}
my_dict2 = {"scName": "RSVM", "City": "Dhanbad"}

# Merging key-value pairs of my_dict2 into my_dict1.
my_dict1.update(my_dict2)
print(my_dict1)
Output:
       {'Name': 'Mahika', 'Age': 17, 'Gender': 'Female', 'scName': 'RSVM', 'City': 'Dhanbad'}

11. values():

This method is used to acquire a list of dictionary values. The basic syntax of using this method is as:

dict.values()

The values() method does not accept anything but returns a list of value available in the dictionary.

Example 11:

# Python program to get a list of value available in the dictionary.
my_dict = {"Name": "Mahika", "Age": 17, "Gender": "Female"}

# Call values() method to get a list of dictionary values.
dict_values = my_dict.values()

print("List of dictionary values: ")
print(dict_values)
Output:
      List of dictionary values: 
      dict_values(['Mahika', 17, 'Female'])

12. str():

This method creates a printable string representation of a dictionary. The basic form of using this method is as follows:

str(dict)

Example 12:

# Python program to print a string representation of dictionary.
my_dict = {"Name": "Mahika", "Age": 17, "Gender": "Female"}

# Call str() function to get string representation of a dictionary.
print("String representation of dictionary: ")
print(str(my_dict))
Output:
      String representation of dictionary: 
      {'Name': 'Mahika', 'Age': 17, 'Gender': 'Female'}

Built-in Functions Used on Dictionaries


There are several built-in functions provided by Python language used on dictionaries for which we can pass an argument as a dictionary. They are as:

  • all()
  • any()
  • len()
  • cmp()
  • sorted()
  • type()

In this tutorial, we have discussed all the dictionary methods and built-in functions in Python with the help of examples. Hope that you will have understood the basic points of each dictionary method and practiced all example programs based on methods. In the next, we will learn about nested dictionary in Python with example programs.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love