Dictionaries in Python

Python में data को key-value pair के रूप में store करने के लिए Dictionary का उपयोग किया जाता है।

यह एक बहुत powerful data structure है, क्योंकि इसमें data को index की बजाय key के माध्यम से access किया जाता है।
Dictionary का use तब किया जाता है जब हमें structured और meaningful data store करना हो।

Dictionary क्या होता है

Dictionary key-value pairs का एक collection होता है, जिसे curly brackets { } के अंदर लिखा जाता है।

हर key के साथ एक value जुड़ी होती है।

Example

student = {
"name": "Rahul",
"age": 20,
"course": "BCA"
}
print(student)

Output

{'name': 'Rahul', 'age': 20, 'course': 'BCA'}

Dictionary की विशेषताएँ

  • Key-value pair में data store होता है
  • Keys unique होती हैं
  • Mutable होता है (change किया जा सकता है)
  • Ordered होता है (Python 3.7 के बाद)
  • Different data types store कर सकता है

Values access करना

Dictionary में values को key की मदद से access किया जाता है।

student = {
"name": "Rahul",
"age": 20
}
print(student["name"])

Output

Rahul

get() method

print(student.get("age"))

यह method error नहीं देता, यदि key मौजूद न हो।

Dictionary को modify करना

Value change करना

student = {
"name": "Rahul",
"age": 20
}
student["age"] = 21
print(student)

New key-value add करना

student["city"] = "Delhi"

Dictionary Methods

1. keys()

print(student.keys())

2. values()

print(student.values())

3. items()

print(student.items())

Dictionary पर loop

student = {
"name": "Rahul",
"age": 20
}
for key in student:
print(key, student[key])

Real-life Example: Student details

student = {
"name": "Amit",
"marks": 85,
"result": "Pass"
}
print(student["name"])
print(student["marks"])

Explanation
यह example student की information को structured form में store करता है।


Real-life Example: Product details

product = {
"name": "Laptop",
"price": 50000,
"stock": 10
}
print("Price:", product["price"])

Explanation
यह example e-commerce system जैसा data structure दिखाता है।


Nested Dictionary

Dictionary के अंदर dictionary भी हो सकती है।

data = {
"student1": {"name": "Rahul", "marks": 80},
"student2": {"name": "Amit", "marks": 90}
}
print(data["student1"]["name"])

Output

Rahul

Common mistakes

  1. duplicate keys use करना
  2. wrong key access करना (KeyError)
  3. list की तरह indexing करने की कोशिश करना

Simple complete program

student = {}
student["name"] = input("Enter name: ")
student["age"] = input("Enter age: ")
print(student)

इस topic की मुख्य बात

Dictionary Python का एक powerful data structure है, जो key-value pair के रूप में data को store और manage करता है।

इस topic में student यह सीखता है:

  • dictionary क्या होता है
  • values को access और modify करना
  • dictionary methods
  • loop के साथ use
  • real-life applications

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top