Example 1:Basic Dictionary
# Example 1: Basic dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}
Example 2:Accessing Dictionary Values
# Example 2: Accessing dictionary values
person = {"name": "John", "age": 30, "city": "New York"}
print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])
# Output:
# Name: John
# Age: 30
# City: New York
Example 3:Accessing Dictionary Values
# Example 3: Adding and modifying dictionary items
person = {"name": "John", "age": 30}
person["city"] = "New York" # Adding a new item
person["age"] = 31 # Modifying an existing item
print(person)
# Output: {'name': 'John', 'age': 31, 'city': 'New York'}
Example 4:Nested Dictionaries
# Example 4: Nested dictionaries
person = {
"name": "John",
"age": 30,
"address": {"city": "New York", "zip": "10001"}
}
print(person)
# Output: {'name': 'John', 'age': 30, 'address': {'city': 'New York', 'zip': '10001'}}
Example 5:Dictionary Methods
# Example 5: Dictionary methods
person = {"name": "John", "age": 30, "city": "New York"}
print("Keys:", person.keys())
print("Values:", person.values())
print("Items:", person.items())
# Output:
# Keys: dict_keys(['name', 'age', 'city'])
# Values: dict_values(['John', 30, 'New York'])
# Items: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
Example 6:Dictionary Comprehension
# Example 6: Dictionary comprehension
squares = {x: x*x for x in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example 7:Deleting Items from Dictionary
# Example 7: Deleting items from dictionary
person = {"name": "John", "age": 30, "city": "New York"}
del person["age"] # Deleting an item
print(person)
# Output: {'name': 'John', 'city': 'New York'}
Example 8:Copying Dictionaries
# Example 8: Copying dictionaries
person = {"name": "John", "age": 30, "city": "New York"}
person_copy = person.copy()
print(person_copy)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}
Example 9:Merging Dictionaries
# Example 9: Merging dictionaries
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "country": "USA"}
merged_dict = {**dict1, **dict2}
print(merged_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
Example 10:Using Different Data Types as Keys
# Example 10: Using different data types as keys
mixed_dict = {1: "one", "two": 2, (3, 4): "tuple"}
print(mixed_dict)
# Output: {1: 'one', 'two': 2, (3, 4): 'tuple'}