π Python Dictionary β KeyβValue Data Structure
Introduction π
A dictionary in Python is an unordered collection of keyβvalue pairs. Each key must be **unique**, and it is used to access the associated value. Dictionaries are extremely useful for structured data, configurations, JSON, and fast lookups.
Note
π‘ Dictionaries use { key: value } syntax and are mutable (changeable).
1. Creating Dictionaries π§±
create_dict.py
# Empty dictionary
empty_dict = {}
# Dictionary with values
student = {
"name": "Sathish",
"age": 25,
"city": "Chennai"
}
# Using dict() constructor
user = dict(username="admin", password="1234")
# Mixed data types
data = {
"id": 101,
"active": True,
"roles": ["admin", "editor"]
}2. Accessing Dictionary Values π
access_dict.py
student = {"name": "Sathish", "age": 25}
print(student["name"]) # Sathish
print(student.get("age")) # 25
print(student.get("city")) # None (no error)Note
βοΈ dict["key"] throws an error if key does not exist
βοΈ dict.get() returns None safely
βοΈ dict.get() returns None safely
3. Modifying Dictionary Values βοΈ
modify_dict.py
student = {"name": "Sathish", "age": 25}
student["age"] = 26
student["city"] = "Chennai" # Add new key
print(student)4. Removing Items β
pop() β Remove by key
pop_key.py
student.pop("age")popitem() β Remove last inserted item
popitem.py
student.popitem()del β Remove key
del_key.py
del student["name"]clear() β Remove all
clear_dict.py
student.clear()5. Looping Through Dictionaries π
Loop keys
dict_keys_loop.py
for key in student:
print(key)Loop values
dict_values_loop.py
for value in student.values():
print(value)Loop keyβvalue pairs
dict_items_loop.py
for key, value in student.items():
print(key, value)6. Dictionary Methods π§°
| Method | Description |
|---|---|
| keys() | Returns all keys |
| values() | Returns all values |
| items() | Returns key-value pairs |
| get() | Safe value access |
| update() | Update multiple values |
| pop() | Removes a key |
| clear() | Clears dictionary |
7. Using update() to Modify Multiple Values π οΈ
dict_update.py
student = {"name": "Sathish", "age": 25}
student.update({"age": 26, "city": "Chennai"})
print(student)8. Nested Dictionaries π§©
nested_dict.py
students = {
1: {"name": "Sathish", "age": 25},
2: {"name": "Kumar", "age": 22}
}
print(students[1]["name"])9. Dictionary Comprehension β‘
dict_comprehension.py
squares = {x: x*x for x in range(1, 6)}
print(squares)Note
βοΈ Makes dictionary creation compact and powerful.
10. Checking If Key or Value Exists π
dict_membership.py
student = {"name": "Sathish", "age": 25}
print("name" in student) # True
print("Sathish" in student.values()) # True11. Real-World Examples π
Storing JSON-like data
json_like.py
product = {
"id": 101,
"name": "Laptop",
"price": 45000,
"stock": 10
}Counting frequency of words
word_count.py
sentence = "apple banana apple mango banana apple"
words = sentence.split()
count = {}
for w in words:
count[w] = count.get(w, 0) + 1
print(count)Login system
login_system.py
users = {"admin": "1234", "user": "abcd"}
username = input("Enter username: ")
password = input("Enter password: ")
if username in users and users[username] == password:
print("Login successful")
else:
print("Invalid credentials")Conclusion π
>>βDictionaries make data structured, fast, and easy to manage β a true powerhouse in Python.β β¨
You now understand Python Dictionaries completely! Want the next topic? Try List Comprehension, Functions, String Methods, or File Handling. Just tell me! π