Python Remove Dictionary Items

Introduction

Removing items from a Python dictionary means deleting key-value pairs. Python provides multiple ways to remove dictionary items including del statement, pop(), popitem(), and clear() methods. This tutorial explains each method with examples.

Python dictionary से आइटम हटाने का मतलब key-value जोड़े को डिलीट करना है। Python में आइटम हटाने के लिए कई तरीके हैं जैसे del स्टेटमेंट, pop(), popitem(), और clear() मेथड्स। इस ट्यूटोरियल में हम हर एक तरीके को उदाहरणों के साथ समझेंगे।

Methods to Remove Dictionary Items

  • del Statement - Delete a key-value pair by key
  • pop(key[, default]) - Remove a key and return its value
  • popitem() - Remove and return last inserted key-value pair
  • clear() - Remove all items from dictionary
  • del स्टेटमेंट - key के द्वारा आइटम हटाएं
  • pop(key[, default]) - key हटाएं और value वापस पाएं
  • popitem() - आखिरी जोड़ा हुआ key-value जोड़ा हटाएं और वापस पाएं
  • clear() - डिक्शनरी के सभी आइटम हटाएं
Example 1: Remove Item Using del
my_dict = {'name': 'Ravi', 'age': 30, 'city': 'Delhi'}
del my_dict['age']
print(my_dict)

Use del statement to remove key 'age' and its value.

<code>del</code> स्टेटमेंट से key 'age' और उसकी value हटाएं।

Output:

{'name': 'Ravi', 'city': 'Delhi'}
Example 2: Remove Item Using pop()
my_dict = {'name': 'Ravi', 'age': 30}
age = my_dict.pop('age')
print(age)
print(my_dict)

pop('age') removes 'age' key and returns its value.

<code>pop('age')</code> 'age' key हटाता है और उसकी value वापस करता है।

Output:

30
{'name': 'Ravi'}
Example 3: Using pop() with Default Value
my_dict = {'name': 'Ravi'}
age = my_dict.pop('age', 'Not Found')
print(age)
print(my_dict)

If key doesn't exist, pop returns default value instead of error.

अगर key मौजूद नहीं है तो pop default value लौटाता है, error नहीं।

Output:

Not Found
{'name': 'Ravi'}
Example 4: Remove Last Item Using popitem()
my_dict = {'name': 'Ravi', 'age': 30}
item = my_dict.popitem()
print(item)
print(my_dict)

popitem() removes last inserted key-value pair and returns it as a tuple.

<code>popitem()</code> आखिरी जोड़ा हुआ key-value जोड़ा हटाता है और टुपल के रूप में लौटाता है।

Output:

('age', 30)
{'name': 'Ravi'}
Example 5: Remove All Items Using clear()
my_dict = {'name': 'Ravi', 'age': 30}
my_dict.clear()
print(my_dict)

clear() removes all items, leaving an empty dictionary.

<code>clear()</code> सभी आइटम हटाता है, खाली dictionary छोड़ देता है।

Output:

{}