02 CDT - 09 Dictionary Manipulation Methods

Dictionary Methods for Modifying and Deleting Key-Value Pairs

  • pop(k [,v]): Removes the key k and its value, returning the value. If key not found, returns v or raises a KeyError.
  • del dict[key]: Deletes the key-value pair associated with key.
  • clear(): Removes all key-value pairs from the dictionary.
  • copy(): Returns a shallow copy of the dictionary.
  • fromkeys(s [,v]): Creates a new dictionary with keys from sequence s and assigns them the default value v.
  • update(x): Updates the dictionary with key-value pairs from another dictionary or iterable.
  • setdefault(k, [,v]): Returns the value for key k or inserts it with the default value v if it does not exist.

dict.pop(k [,v])

The pop() method is used to remove a key-value pair from the dictionary based on the specified key k. When the key is found, it is removed and its associated value is returned.

If the key does not exist, the method will return a default value v if specified. If no default value is provided and the key is not found, a KeyError will be raised.

Syntax:

dict.pop(k [,v])
  • k: The key that you want to remove from the dictionary.
  • v: (Optional) The default value to return if the key is not found.
>>> score = {'Test1': {'Dhawan': 84, 'Kohli': 200}, 'Test2': {'Dhawan': 50}}

>>> score.pop('Test1')
{'Dhawan': 84, 'Kohli': 200}

>>> score  # Popped value removed
{'Test2': {'Dhawan': 50}}

>>> score.pop('Test2', 'Test not Found')
{'Dhawan': 50}

>>> score.pop('Test3', 'Test not Found')
'Test not Found'
  • score.pop('Test1') removes the dictionary associated with the key "Test1" and returns it.
  • score.pop('Test3', 'Test not Found') returns the default message "Test not Found" because the key "Test3" does not exist in the dictionary.

del dict[key]

The del statement is used to delete a specific key-value pair from a dictionary. If the key is found, it removes the pair from the dictionary. If the key does not exist, a KeyError is raised.

Syntax:

del dict[key]
  • key: The key whose key-value pair you want to delete.
>>> score = {'Test1': {'Dhawan': 84, 'Kohli': 200}, 'Test2': {'Dhawan': 50}}

>>> del score["Test2"]["Dhawan"]
>>> score
{'Test1': {'Dhawan': 84, 'Kohli': 200}, 'Test2': {}}

>>> del score["Test2"]
>>> score
{'Test1': {'Dhawan': 84, 'Kohli': 200}}

>>> del score["Test1"]["Kohli"]
>>> score
{'Test1': {'Dhawan': 84}}

dict.clear()

The clear() method is used to remove all key-value pairs from the dictionary, effectively emptying the dictionary.

Syntax:

dict.clear()
>>> score = {'Test1': {'Dhawan': 84, 'Kohli': 200}, 'Test2': {'Dhawan': 50}}

>>> score.clear()
>>> score
{}
  • After calling score.clear(), the dictionary is emptied and becomes an empty dictionary {}.

dict.copy()

The copy() method is used to create a shallow copy of the dictionary. This means a new dictionary is created, but the values within the dictionary are still references to the original objects.

Syntax:

dict_n = dict.copy()
>>> original_dict = {'color': 'blue', 'points': 5}
>>> dict_n = original_dict.copy()

>>> dict_n
{'color': 'blue', 'points': 5}

>>> dict_n['color'] = 'green'
>>> dict_n
{'color': 'green', 'points': 5}
>>> original_dict
{'color': 'blue', 'points': 5}
  • After copying original_dict, we modify the value of "color" in the copied dictionary dict_n, but the original dictionary remains unchanged.

dict.fromkeys(s [,v])

The fromkeys() method is used to create a new dictionary with keys from a given sequence s. All the keys in the new dictionary are assigned the same value v. If no value is provided, the default value is None.

Syntax:

dict_n = dict.fromkeys(s [,v])
  • s: A sequence (like a list, tuple, or string) containing the keys for the new dictionary.
  • v: (Optional) The value to be assigned to each key. If not provided, it defaults to None.
>>> keys = ['a', 'b', 'c']
>>> new_dict = dict.fromkeys(keys, 0)

>>> new_dict
{'a': 0, 'b': 0, 'c': 0}

>>> new_dict2 = dict.fromkeys(keys)

>>> new_dict2
{'a': None, 'b': None, 'c': None}
  • dict.fromkeys(keys, 0) creates a new dictionary where each key from the list keys has the value 0.
  • dict.fromkeys(keys) creates a new dictionary where each key has the value None by default.

dict.update(x)

The update() method is used to update the dictionary by adding the key-value pairs from another dictionary x (or from an iterable of key-value pairs). If a key in the original dictionary already exists, its value is updated with the new value.

Syntax:

dict.update(x)
  • x: Another dictionary or an iterable of key-value pairs (like a list of tuples) that you want to add or update in the dictionary.
>>> score = {'Test1': {'Dhawan': 84, 'Kohli': 200}}

>>> new_scores = {'Test1': {'Rahul': 60}, 'Test2': {'Dhawan': 50}}

>>> score.update(new_scores)
>>> score
{'Test1': {'Dhawan': 84, 'Kohli': 200, 'Rahul': 60}, 'Test2': {'Dhawan': 50}}
  • The update() method adds the key-value pairs from new_scores to the original score dictionary. If any keys exist in both dictionaries (like "Test1"), the values are updated accordingly.

dict.setdefault(k, [,v])

The setdefault() method is used to get the value associated with the key k. If the key exists in the dictionary, its value is returned. If the key does not exist, it will be added to the dictionary with the default value v. If no default value is specified, the default value None is used.

Syntax:

dict.setdefault(k, [,v])
  • k: The key whose value you want to retrieve.
  • v: (Optional) The default value to assign to the key if it is not already in the dictionary.
>>> score = {'Test1': {'Dhawan': 84, 'Kohli': 200}}

>>> score.setdefault('Test2', {'Dhawan': 50})
>>> score
{'Test1': {'Dhawan': 84, 'Kohli': 200}, 'Test2': {'Dhawan': 50}}

>>> score.setdefault('Test1', {'Kohli': 250})
>>> score
{'Test1': {'Dhawan': 84, 'Kohli': 200}, 'Test2': {'Dhawan': 50}}
  • score.setdefault('Test2', {'Dhawan': 50}) adds "Test2" with its default value because "Test2" does not exist in the dictionary.
  • score.setdefault('Test1', {'Kohli': 250}) does not modify "Test1" because it already exists.