python


A dictionary in Python is an unordered, mutable collection that stores data as key-value pairs. Unlike lists or tuples (which store values by index), dictionaries let you access data using keys, making them ideal for structured data.



A dictionary in Python looks like this:

person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}


Here:

* `"name"`, `"age"`, and `"city"` are keys
* `"Alice"`, `25`, `"New York"` are values



 Creating a Dictionary

 
# Empty dictionary
my_dict = {}

# With data
student = {"name": "John", "marks": 85}




 Accessing Dictionary Elements

Use keys to access values:

 
print(student["name"])       # John
print(student.get("marks"))  # 85


`get()` is safer because it returns `None` instead of an error if the key doesn’t exist.



 Adding and Updating Values

student["age"] = 20         # Adding a new key-value pair
student["marks"] = 90       # Updating existing value
print(student)              # {'name': 'John', 'marks': 90, 'age': 20}




 Removing Items

* `pop(key)` → Removes a key
* `popitem()` → Removes last key-value pair
* `clear()` → Removes all items

Example:

 
student.pop("age")
print(student)




Looping Through a Dictionary

 
for key in student:
    print(key, student[key])

# Using items()
for key, value in student.items():
    print(key, value)




 Dictionary Methods

* `keys()` → Returns all keys
* `values()` → Returns all values
* `items()` → Returns key-value pairs
* `update()` → Adds items from another dictionary

Example:

python
print(student.keys())    # dict_keys(['name', 'marks'])
print(student.values())  # dict_values(['John', 90])




 Nested Dictionaries

A dictionary inside another dictionary:

python
users = {
    "user1": {"name": "Alice", "age": 25},
    "user2": {"name": "Bob", "age": 30}
}

print(users["user1"]["name"])  # Alice




 Dictionary Comprehension

Create dictionaries in one line:

python
squares = {x: x*x for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}




 Summary

* Dictionaries store key-value pairs.
* Mutable – you can add, remove, or update items.
* Use methods like `keys()`, `values()`, `items()`.
* Great for structured data like user info, configurations.