Dictionaries

# Creating an empty dictionary
dict1 = {}

# Creating a dictionary with initial key-value pairs
dict2 = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Using the dict() constructor
dict3 = dict(name="Bob", age=30, city="Los Angeles")

print(dict1)
print(dict2)
print(dict3)
{}
{'name': 'Alice', 'age': 25, 'city': 'New York'}
{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

print(person["name"])
print(person.get("age"))

# Accessing a non-existing key using get()
print(person.get("address", "Address not found"))
Alice
25
Address not found
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Modifying existing key
person["age"] = 26

# Adding a new key-value pair
person["email"] = "[email protected]"

print(person)
{'name': 'Alice', 'age': 26, 'city': 'New York', 'email': '[email protected]'}
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Removing a key-value pair using del
del person["city"]

# Removing a key-value pair using pop()
email = person.pop("email", "Email not found")

print(person)
print("Email:", email)
{'name': 'Alice', 'age': 25}
Email: Email not found
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

for key in person:
    print(key)
name
age
city
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

for value in person.values():
    print(value)
Alice
25
New York
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

for key, value in person.items():
    print(f"Key: {key}, Value: {value}")
Key: name, Value: Alice
Key: age, Value: 25
Key: city, Value: New York
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Check if key exists
if "name" in person:
    print("Name exists in the dictionary.")
else:
    print("Name does not exist in the dictionary.")
Name exists in the dictionary.