Python में dictionary एक built-in data structure है, जिसका उपयोग data को key-value pairs के रूप में store करने के लिए किया जाता है। इसका मतलब है कि आपको elements को store करने के लिए एक key और उस key से जुड़ी हुई value की जरूरत होती है। इसमें हर key की एक unique value होती है।
Dictionary की कुछ मुख्य विशेषताएँ (features) निम्नलिखित हैं:-
- Unordered: Dictionary में elements का कोई एक विशेष order नहीं होता।
- Mutable: Dictionary को change किया जा सकता है। इसमें आप नए elements को add, delete या modify कर सकते हैं।
- Indexed: Dictionary के items को keys के माध्यम से access किया जाता है, ना कि indices के माध्यम से जैसा कि list या tuple में होता है।
- Key must be unique: Dictionary में कोई भी key duplicate नहीं हो सकती है। अगर एक ही key दो बार assign की जाती है, तो value update हो जाती है, और पुरानी value replace हो जाती है।
- Dynamic: डिक्शनरी dynamic होती है, यानी आप items को run-time के दौरान add, modify, या delete कर सकते हैं।
Python में Dictionary कैसे बनाते हैं?
Python में Dictionary में एक key होती है, और उसी key से जुड़ी एक value होती है। Dictionary को key-value pair के रूप में store किया जाता है।
Python में dictionary बनाने के लिए curly braces {} का उपयोग किया जाता है। Key और value को colon : द्वारा अलग किया जाता है। दो से अधिक key-value pairs को comma , द्वारा अलग किया जाता है।
Example:
student = {
"name": "Pankaj",
"age": 20,
"course": "Computer Science"
}
इस example में, student एक dictionary है, जिसमें तीन key-value pairs हैं:
- “name” की value “Pankaj” है।
- “age” की value 20 है।
- “course” की value “Computer Science” है।
Dictionary में Values कैसे Access करें?
Dictionary में values को access करने के लिए key का उपयोग किया जाता है। हम key को square brackets [] के अंदर लिखकर value एक्सेस कर सकते हैं।
Example:
student = {
"name": "Yugal",
"age": 30,
"course": "Computer Science"
}
print(student["name"]) # Output: Yugal
print(student["age"]) # Output: 30
Dictionary में नए Items कैसे Add करें?
अगर आप dictionary में नए key-value pair को add करना चाहते हैं, तो आप सीधे key के माध्यम से assignment operator = का उपयोग कर सकते हैं।
Example:
student = {
"name": "Yugal",
"age": 30,
"course": "Computer Science"
}
student["grade"] = "A" # Adding a new key-value pair
print(student)
Output:
{'name': 'Yugal', 'age': 30, 'course': 'Computer Science', 'grade': 'A'}
Dictionary में Items कैसे Remove करें?
Python में dictionary से items को remove करने के लिए कई methods हैं:
1:- del: इस method का उपयोग किसी key को dictionary से हमेशा के लिए remove करने के लिए किया जाता है।
del student["age"]
print(student)
2:- pop(): इस method का उपयोग एक key-value pair को remove करने के साथ-साथ उसकी value भी return करने के लिए किया जाता है।
removed_value = student.pop("course")
print(removed_value) # Output: Computer Science
print(student)
3:- clear(): इस method का उपयोग dictionary के सारे items को remove करने के लिए किया जाता है।
student.clear()
print(student) # Output: {}
इसे भी पढ़ें:-
