Dictionary kya hai?
Python me dictionary ek aisa collection hai jisme data key-value pairs ke form me store hota hai. Matlab har value ka ek naam (key) hota hai.
Dictionary banane ka example:
# Example of a dictionary
student = {
"name": "Amit",
"age": 21,
"course": "Python"
}
print(student)
Output:
{'name': 'Amit', 'age': 21, 'course': 'Python'}
Dictionary ke elements access karna
print(student["name"]) # Amit
print(student["age"]) # 21
Dictionary update karna
student["age"] = 22
print(student)
Output:
{'name': 'Amit', 'age': 22, 'course': 'Python'}
Naya key-value add karna
student["grade"] = "A"
print(student)
Output:
{'name': 'Amit', 'age': 22, 'course': 'Python', 'grade': 'A'}
Key ko remove karna
del student["course"]
print(student)
Output:
{'name': 'Amit', 'age': 22, 'grade': 'A'}
Useful Dictionary Methods
print(student.keys()) # dict_keys(['name', 'age', 'grade'])
print(student.values()) # dict_values(['Amit', 22, 'A'])
print(student.items()) # dict_items([('name', 'Amit'), ('age', 22), ('grade', 'A')])
Loop through Dictionary
for key, value in student.items():
print(key, ":", value)
Output:
name : Amit
age : 22
grade : A
Next Step
Ab seekhte hain Iteration on Lists, Tuples & Dictionaries, jahan hum collections ko loop ke saath traverse karenge.