Dictionaries in Python

What is a Dictionary?

A dictionary is an unordered collection of key-value pairs in Python. Keys must be unique and immutable, values can be of any type. Dictionaries are mutable and widely used for fast lookups.

Creating Dictionaries

my_dict = {"name": "Alice", "age": 30}
empty_dict = {}  # Empty dictionary

Examples

# 1. Creating and printing a dictionary
person = {"name": "John", "age": 25, "city": "New York"}
print(person)  # Output: {'name': 'John', 'age': 25, 'city': 'New York'}
  
# 2. Accessing values by key
print(person["name"])  # Output: John
  
# 3. Adding or updating key-value pairs
person["email"] = "john@example.com"
person["age"] = 26
print(person)
  
# 4. Removing a key-value pair
del person["city"]
print(person)
  
# 5. Iterating through keys and values
for key, value in person.items():
    print(key, ":", value)