Python- Built-in Methods for Dictionaries

In this tutorial, I will discuss about all the built-in methods for dictionaries in python.

Built-in Methods for Dictionaries

Python provides special built-in methods for dictionary objects.

So let's see each of these methods and use.

clear( )

The clear() method removes all the elements from the dictionary and makes it an empty dictionary.

Syntax of clear() method is :

dictionary.clear( )

parameter : The clear() method does not take any parameter.

return : The clear() method does not return anything but it removes all the elements from the dictionary and makes it an empty dictionary.

Example :

dict1 = {1:2, 3:4, 5:6}
print("Original dictionary : ",dict1)
dict1.clear()
print("After clear() : ",dict1)
Original dictionary :  {1: 2, 3: 4, 5: 6}
After clear() :  {}

copy( )

The copy() method is used to get a true copy of the dictionary. It copies the original dictionary into a new dictionary and if we update any of the dictionary then it will not affect other dictionary.
Syntax of copy() method is :

Dict1 = dict.copy( )

parameter : The copy() method does not take any parameter.

return : The copy() method returns a true copy of the list which means that both the dictionaries are independent.

Example :

dict1 = {1:'a', 2:'b',3:'c'}
dict2 = dict1.copy()
print("dict1 = ",dict1)
print("dict2 = ",dict2)
dict1[2] = 'd'
print("After updating dict1")
print("dict1 = ",dict1)
print("dict2 = ",dict2)
dict1 =  {1: 'a', 2: 'b', 3: 'c'}
dict2 =  {1: 'a', 2: 'b', 3: 'c'}
After updating dict1
dict1 =  {1: 'a', 2: 'd', 3: 'c'}
dict2 =  {1: 'a', 2: 'b', 3: 'c'}

fromkeys( )

The fromkeys() method creates a new dictionary with the elements from the iterable given in parameter as keys. It also takes an optional parameter value which is a single object which is given as value to all the keys of the new dictionary. If we do not pass any value then all the keys will have None as their value by default.
Syntax of fromkeys() method is :

Dict1 = dict.fromkeys(iterable, value = None(default))

parameter : The fromkeys() method takes an iterable python object as a parameter whose elements are used as keys for the new dictionary. It also takes an optional parameter value which is used as value for all the keys in the dictionary. If we do not pass any value then it takes None as default value for all the keys.

return : The fromkeys() method returns a new dictionary with keys from the iterable python object given as parameter and their value as given optional parameter.

Example :

list1 = [1,2,3,4]
list2 = ['a','b','c']
Dict1 = {}
print("Using fromkeys without value : ",Dict1.fromkeys(list1))
print("Using fromkeys with value : ",Dict1.fromkeys(list2, 1))
Using fromkeys without value :  {1: None, 2: None, 3: None, 4: None}
Using fromkeys with value :  {'a': 1, 'b': 1, 'c': 1}

key( )

The key() method is used to get value for a key from the dictionary. The key is passed as a parameter and the method returns value corresponding to that key. If the key is not present in the dictionary then it returns None by default. It also has an optional parameter default which is used when the key is not present in the dictionary and it returns the value passed as default to the method.

Syntax of key() method is :

dict.key(key, default = None(default))

parameter : The key() method takes a key as parameter whose corresponding value we want from the method. It also takes an optional default parameter which is used when the key is not present in the dictionary.

return : The key() method returns the value corresponding to the key given as parameter and if the key is not present then returns the value given as default parameter and if not given it returns None.

Example :

dict3 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
print("Original dictionary : ",dict3)
print("dict3.get(3) : ",dict3.get(3))
print("dict3.get(8) : ",dict3.get(8))
print("dict3.get(10,'def') : ",dict3.get(10,'def'))
Original dictionary :  {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
dict3.get(3) :  c
dict3.get(8) :  None
dict3.get(10,'def') :  def

items( )

The items() method is used to get the items (key:value) pairs of a dictionary in a dict_items object. This object contains key,value pairs as tuple elements. We can convert this output into iterable objects like list or tuple using which we can access each element (tuple of key:value pairs).

Syntax of items() method is :

dict.items( )

parameter : The items() method does not take any parameter.

return : The items() method returns a dict_items object with key:value pairs as tuple elements. We can convert this object into iterable objects like list or tuple if we wish to access each element (key:value pair tuple) of the object.

Example :

print("Original list : ", dict3)
items = dict3.items()
print("Items() method : ",items)
list_items = list(items)
print("After converting to list : ",list_items)
print("list_items[2] : ", list_items[2])
Original list :  {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
Items() method :  dict_items([(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')])
After converting to list :  [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
list_items[2] :  (3, 'c')

keys( )

The keys() method is used to get the keys of a dictionary in a dict_keys object. This object contains keys in form of list inside the dict_keys object. We can convert this output into iterable objects like list or tuple using which we can access each key of the dictionary.
Syntax of keys() method is :

dict.keys( )

parameter : The keys() method does not take any parameter.

return : The keys() method returns a dict_keys object with ke in form of a list inside the dict_keys object. We can convert this object into iterable objects like list or tuple if we wish to access each element or key of the dictionary.

Example :

print("Original list : ", dict3)
keys = dict3.keys()
print("keys() method : ",keys)
list_keys = list(keys)
print("After converting to list : ",list_keys)
print("list_keys[2] : ", list_keys[4])
Original list :  {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
keys() method :  dict_keys([1, 2, 3, 4, 5])
After converting to list :  [1, 2, 3, 4, 5]
list_keys[2] :  5

values( )

The values() method is used to get the keys of a dictionary in a dict_values object. This object contains values in form of list inside the dict_values object. We can convert this output into iterable objects like list or tuple using which we can access each value of the dictionary.
Syntax of values() method is :

dict.values( )

parameter : The values() method does not take any parameter.

return : The values() method returns a dict_values object with values in form of a list inside the dict_values object. We can convert this object into iterable objects like list or tuple if we wish to access each element or value of the dictionary.

Example :

print("Original list : ", dict3)
values = dict3.values()
print("values() method : ",values)
list_values = list(values)
print("After converting to list : ",list_values)
print("list_values[2] : ", list_values[4])
Original list :  {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
values() method :  dict_values(['a', 'b', 'c', 'd', 'e'])
After converting to list :  ['a', 'b', 'c', 'd', 'e']
list_values[2] :  e

pop( )

The pop() method removes the key:value pair and returns the corresponding value of the key passed as a parameter form the dictionary. If the key is not present in the dictionary then it raises KeyError or returns a default value given as optional parameter to the method.

Syntax of pop() method is :

dict.pop(key, default(optional))

parameter : The pop() method takes a key value as parameter which we want to remove from the dictionary. It also takes an optional default parameter which is used when the key is not present in the dictionary.

return : The pop() method returns the value corresponding to the key given as parameter. If the key is not found it returns the optional default parameter or it will raise a KeyError.

Example :

print("Original dictionary : ",dict3)
print("dict3.pop(3) : ",dict3.pop(3))
print("dict3.pop(9,'default') : ", dict3.pop(9,'default'))
print("dict3.pop(11) : ", dict3.pop(11))
Original dictionary :  {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
dict3.pop(3) :  c
dict3.pop(9,'default') :  default

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

 in 
      2 print("dict3.pop(3) : ",dict3.pop(3))
      3 print("dict3.pop(9,'default') : ", dict3.pop(9,'default'))
----> 4 print("dict3.pop(11) : ", dict3.pop(11))

KeyError: 11

popitem( )

The popitem() method removes and returns a key:value pair form the dictionary in form of a tuple with key and value as elements. If the dictionary is empty then it raises KeyError.
Syntax of popitem() method is :

dict.popitem( )

parameter : The popitem() method does not take any parameter.

return : The popitem() method returns a key:value pair from the dictionary in the form of a tuple. If the dictionary is empty then it raises KeyError.

Example :

dict4 = {1:2, 2:4, 3:6}
print("Original dictionary : ",dict4)
print("dict4.popitem() : ",dict4.popitem())
print("dict4.popitem() : ",dict4.popitem())
print("dict4.popitem() : ",dict4.popitem())
print("dict4.popitem() : ",dict4.popitem())
Original dictionary :  {1: 2, 2: 4, 3: 6}
dict4.popitem() :  (3, 6)
dict4.popitem() :  (2, 4)
dict4.popitem() :  (1, 2)

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

 in 
      4 print("dict4.popitem() : ",dict4.popitem())
      5 print("dict4.popitem() : ",dict4.popitem())
----> 6 print("dict4.popitem() : ",dict4.popitem())

KeyError: 'popitem(): dictionary is empty'

setdefault( )

The setdefault() method is used for updating the dictionary by adding a key:value pair. The method takes a key as parameter.

If the key already exists then the dictionary will not be updated and the method will return its corresponding value, otherwise a new key:value pair will be added to the dictionary and the method will return its corresponding value.

The value in this case is taken from a default optional parameter passed to the method. If this parameter is not given then it will give None as value to the key.

Syntax of setdefault() method is :

dict.setdefault(key, default (optional))

parameter : The setdefault() method takes a key as parameter. If it exists then the dictionary is not updated, otherwise a new key:value pair is added to the dictionary. The value is taken from optional parameter default. If this parameter is not passed then the method takes None as value for the new key.

return : The setdefault() method returns the corresponding value for the key passed as parameter if the key already exists. If the key does not exists then it adds the key:value pair to the dictionary and returns the new value.

Example :

dict5 = {1:'a', 2:'b', 3:'c'}
print("Original dictionary : ",dict5)
print("dict5.setdefault(2) : ",dict5.setdefault(2))
print("dict5.setdefault(4) : ",dict5.setdefault(4))
print("After new key : ",dict5)
print("dict5.setdefault(5,'def') : ",dict5.setdefault(5,'def'))
print("After new key : ",dict5)
Original dictionary :  {1: 'a', 2: 'b', 3: 'c'}
dict5.setdefault(2) :  b
dict5.setdefault(4) :  None
After new key :  {1: 'a', 2: 'b', 3: 'c', 4: None}
dict5.setdefault(5,'def') :  def
After new key :  {1: 'a', 2: 'b', 3: 'c', 4: None, 5: 'def'}

update( )

The update() method is used for updating the dictionary using another dictionary or iterable (tuple). This method takes a dictionary as a parameter and adds all the elements to the dictionary if the key is not present, and if the key is present then it updates the corresponding value with new value.
Syntax of update() method is :

dict.update(iterable)

parameter : The update() method takes a dictionary as a parameter and adds all the elements to the dictionary if keys are not present then the dictionary. If any of the keys are present in the dictionary then it will update the corresponding value with new value.

return : The update() method does not return anything, it updates the dictionary with new elements using the parameter.

Example :

dict6 = {1:2, 2:4, 3:6}
print("Original dictionary : ",dict6)
dict6.update({4:8, 5:10})
print("After update : ",dict6)
dict6.update(ace=1, b=2)
print("Update without using dictionary : ", dict6)
Original dictionary :  {1: 2, 2: 4, 3: 6}
After update :  {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
Update without using dictionary :  {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 'ace': 1, 'b': 2}

In the above example, if we do not use a dictionary then update() method takes key = value as parameters, and in this way we can only give string or character values as keys,, otherwise it raises a SyntaxError.

Conclusion

In this tutorial we have seen all built-in methods provided by python for dictionary objects with examples.

If you have any questions please comment below, also share your views and suggestions in the comment box.

Pooja is a programmer by profession and love to write articles on Python. She is highly interested in Python, Data Science and Machine Learning. Pooja holds B.E. Computer Engineering degree. She loves teaching and learning new thing.

Leave a Comment