How do you clear an entire dictionary in python?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The clear() method removes all items from the dictionary.

    Syntax:

    dict.clear()

    Parameters:

    The clear() method doesn't take any parameters.

    Returns:

    The clear() method doesn't return any value.

    Examples:

    Input : d = {1: "geeks", 2: "for"} d.clear() Output : d = {}

    Error:

    As we are not passing any parameters there is no chance for any error.

    text = {1: "geeks", 2: "for"}

    text.clear()

    print('text =', text)

    Output:

    text = {}

    How is it different from assigning {} to a dictionary?
    Please refer the below code to see the difference. When we assign {} to a dictionary, a new empty dictionary is created and assigned to the reference. But when we do clear on a dictionary reference, the actual dictionary content is removed, so all references referring to the dictionary become empty.

    text1 = {1: "geeks", 2: "for"}

    text2 = text1

    text1.clear()

    print('After removing items using clear()')

    print('text1 =', text1)

    print('text2 =', text2)

    text1 = {1: "one", 2: "two"}

    text2 = text1

    text1 = {}

    print('After removing items by assigning {}')

    print('text1 =', text1)

    print('text2 =', text2)

    Output:

    After removing items using clear() text1 = {} text2 = {} After removing items by assigning {} text1 = {} text2 = {1: 'one', 2: 'two'}

    Want to delete a dictionary in Python? The Python Dictionary is a data structure used in Python that accepts elements in key-value pair form. In this article, we will be understanding different Ways of deleting a key-value pair from a Python Dictionary.

    The dict.clear() to delete a dictionary in Python

    Python has in-built clear() method to delete a dictionary in Python. The clear() method deletes all the key-value pairs present in the dict and returns an empty dict.

    Syntax:

    Example:

    inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"} print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) inp_dict.clear() print("\nElements of the dict after performing the deletion operation:") print(str(inp_dict))

    Output:

    Elements of the dict before performing the deletion operation: {'B': 'Java', 'D': 'Javascript', 'C': 'Fortan', 'A': 'Python'} Elements of the dict after performing the deletion operation: {}

    Techniques to delete a key-value pair from a Python Dictionary

    The following techniques can be used to delete a key-value pair from a dictionary:

    • Python pop() function
    • Python del keyword
    • In-built Python popitem() method
    • Dictionary Comprehension along with Python items() method

    1. Using pop() method

    Python pop() method can be used to delete a key and a value associated with it i.e. a key-value pair from a dictionary.

    Syntax:

    The pop() method basically accepts a key to be deleted from the dictionary. It deletes the key as well as the value associated with the key from the dict and returns the updated dict.

    Example:

    inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"} print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) pop_item = inp_dict.pop("A") print("\nThe deleted element:") print(str(pop_item)) print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

    In the above snippet of code, we have passed the key – “A” as an argument to the pop() method. Thus, it deletes the key value pair associated with “A”.

    Output:

    Elements of the dict before performing the deletion operation: {'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'} The deleted element: Python Elements of the dict after performing the deletion operation: {'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'} ​

    2. Python del keyword

    Python del is actually a keyword which is basically used for the deletion of objects. As we all are aware that Python considers everything as an object, that is why we can easily use del to delete a dictionary in Python by deleting elements individually.

    Python del keyword can also be used to delete a key-value pair from the input dictionary values.

    Syntax:

    Example 1:

    inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"} print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) del inp_dict["D"] print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

    Output:

    Elements of the dict before performing the deletion operation: {'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'} Elements of the dict after performing the deletion operation: {'A': 'Python', 'B': 'Java', 'C': 'Fortan'}

    Example 2: Deleting a key-value pair from a Nested Dictionary

    Syntax:

    It is possible for us to delete the key-value pair from a nested Python Dictionary. The del keyword serves the purpose with the below syntax:

    del dict[outer-dict-key-name][key-name-associated-with-the-value]

    Example:

    inp_dict = {"Python":{"A":"Set","B":"Dict","C":"Tuple","D":"List"}, "1":"Java","2":"Fortan"} print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) del inp_dict["Python"]["C"] print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

    Thus, here, we delete the key-value pair “C:Tuple” associated with the outer key “Python“.

    Output:

    Elements of the dict before performing the deletion operation: {'Python': {'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List'}, '1': 'Java', '2': 'Fortan'} Elements of the dict after performing the deletion operation: {'Python': {'A': 'Set', 'B': 'Dict', 'D': 'List'}, '1': 'Java', '2': 'Fortan'}

    3. Python popitem() method

    Python popitem() function can be used to delete a random or an arbitrary key-value pair from a Python dict. The popitem() function accepts no arguments and returns the deleted key-value pair from the dictionary.

    Syntax:

    Example:

    inp_dict = {"A":"Python","B":"Java","C":"Fortan","D":"Javascript"} print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) pop_item = inp_dict.popitem() print("\nThe deleted element:") print(str(pop_item)) print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

    Output:

    Elements of the dict before performing the deletion operation: {'A': 'Python', 'B': 'Java', 'C': 'Fortan', 'D': 'Javascript'} The deleted element: ('D', 'Javascript') Elements of the dict after performing the deletion operation: {'A': 'Python', 'B': 'Java', 'C': 'Fortan'}

    4. Python Dict Comprehension along with items() method

    Python items() method along with Dict Comprehension can be used to delete a dictionary in Python.

    Python items() method basically takes no arguments and returns an object containing a list of all the key-value pairs in the particular dictionary.

    Syntax:

    Python Dict Comprehension can be used to create a dictionary by accepting the key-value pairs from a particular iterable.

    Syntax:

    {key: value for key, value in iterable}

    In the context of the deletion of key-value pairs from a dictionary, the items() method can be used to provide the list of key-value pairs to the dict comprehension as an iterable.

    The if statement is used to encounter key-value mentioned ahead of it. If the mentioned key value is encountered, it returns a new dict containing all the key-value pairs excluding the key-value pair associated with the key to be deleted.

    Example:

    inp_dict = {"A":"Set","B":"Dict","C":"Tuple","D":"List", "1":"Java","2":"Fortan"} print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) res_dict = {key:value for key, value in inp_dict.items() if key != "1"} print("\nElements of the dict after performing the deletion operation:\n") print(str(res_dict))

    Output:

    Elements of the dict before performing the deletion operation: {'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'} Elements of the dict after performing the deletion operation: {'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '2': 'Fortan'}

    Delete a Dictionary in Python By Specifying Elements While Iteration

    While dealing with Python Dictionary, we may come across situations wherein we would want a key-value pair to be deleted during the iteration of the dictionary.

    To serve the purpose, we can create a list of the input-dictionary and use a for loop to traverse through the list of the dictionary.

    Syntax:

    Finally, by using an if statement, we would check for the loop to encounter the key to be deleted. As soon as the key is encountered, del keyword can be used to delete the key-value pair.

    Example:

    inp_dict = {"A":"Set","B":"Dict","C":"Tuple","D":"List", "1":"Java","2":"Fortan"} print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) for KEY in list(inp_dict): if KEY =="B": del inp_dict[KEY] print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

    Output:

    Elements of the dict before performing the deletion operation: {'A': 'Set', 'B': 'Dict', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'} Elements of the dict after performing the deletion operation: {'A': 'Set', 'C': 'Tuple', 'D': 'List', '1': 'Java', '2': 'Fortan'}

    Conclusion

    Thus, we have unveiled the different techniques to delete a key-value pair from Python Dictionary.

    References

    • Python Dictionary – JournalDev
    • Python Dictionary – Official Documentation

    How do you clear a dictionary in Python?

    The clear() method removes all items from the dictionary..
    Syntax: dict.clear().
    Parameters: The clear() method doesn't take any parameters..
    Returns: The clear() method doesn't return any value..
    Examples: Input : d = {1: "geeks", 2: "for"} d.clear() Output : d = {}.
    Error: ... .
    Output: text = {}.

    How do I delete an entire dictionary?

    Python has in-built clear() method to delete a dictionary in Python. The clear() method deletes all the key-value pairs present in the dict and returns an empty dict.

    How do I remove all keys from a dictionary?

    Method 2: Delete all Keys from a Dictionary using dict. clear() The clear() method removes all items from the dictionary. The clear() method doesn't return any value.

    What is the function to remove all the contents in a dictionary?

    The clear() method removes all items from a dictionary and makes it empty.

    Chủ đề