|7. Dictionaries in Python
Chapter 7Python Tutorial~1 min read

Dictionaries in Python

Dictionaries — Key-Value Pairs

Dictionary म्हणजे key-value pairs चा collection. प्रत्येक value ला एक unique key असतो. Keys वापरून values access करता येतात. JavaScript च्या Objects सारखे आहे.

Marathi Analogy

Dictionary म्हणजे Aadhar Card सारखे. "name: Rahul Patil", "age: 25", "city: Pune" — प्रत्येक field (key) ला एक value आहे. number ऐवजी नावाने access करतो, हे list पेक्षा वेगळे आहे!

Dictionary बनवणे आणि access करणे

python
# Dictionary बनवणे
person = {
    "name": "Karan",
    "age": 19,
    "city": "Pune",
    "is_student": True
}

# Access करणे
print(person["name"])        # Karan
print(person["age"])         # 19
print(person.get("city"))    # Pune — safe access
print(person.get("phone", "N/A"))  # N/A — key नसेल तर default

Add, Update, Remove

Modify dictionary

python
info = {"name": "Simran", "age": 20}

# ADD नवी key
info["email"] = "simran@gmail.com"
info.update({"city": "Mumbai", "marks": 95})

# UPDATE existing
info["age"] = 21

# REMOVE
del info["marks"]           # specific key delete
popped = info.pop("email")  # delete आणि value return
print(popped)  # simran@gmail.com

print(info)
# {'name': 'Simran', 'age': 21, 'city': 'Mumbai'}

Dictionary Methods

keys(), values(), items()

python
student = {"name": "Rahul", "marks": 85, "grade": "A"}

# सगळ्या keys
print(student.keys())    # dict_keys(['name', 'marks', 'grade'])

# सगळ्या values
print(student.values())  # dict_values(['Rahul', 85, 'A'])

# key-value pairs
print(student.items())   # dict_items([('name','Rahul'), ...])

# सगळ्या key-value pairs loop करणे
for key, value in student.items():
    print(f"{key}: {value}")

Key Points — लक्षात ठेवा

  • Dictionary = {key: value} — unordered key-value store
  • d[key] access करतो, d.get(key, default) — safe access
  • d[key] = val — add/update, del d[key] — delete
  • .keys(), .values(), .items() — iteration साठी
  • Keys unique असतात — duplicate key असेल तर overwrite होतो
0/12 chapters पूर्ण