DICTIONARIES
A dictionary is a mutable, unordered collection of key-value pairs, where each key must be unique. Dictionaries are often used when you want to associate some data (the value) with a particular key for efficient retrieval. Dictionaries are defined using curly braces {}
and colons :
to separate keys and values.
# Creating a dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
# Accessing values by key
print(my_dict['name']) # Output: John
print(my_dict['age']) # Output: 30
# Modifying values
my_dict['age'] = 31
print(my_dict) # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
# Adding a new key-value pair
my_dict['gender'] = 'Male'
print(my_dict) # Output: {'name': 'John', 'age': 31, 'city': 'New York', 'gender': 'Male'}
# Removing a key-value pair
del my_dict['city']
print(my_dict) # Output: {'name': 'John', 'age': 31, 'gender': 'Male'}
# Checking if a key exists
print('age' in my_dict) # Output: True
print('height' in my_dict) # Output: False
# Getting all keys and values
keys = my_dict.keys()
values = my_dict.values()
print(keys) # Output: dict_keys(['name', 'age', 'gender'])
print(values) # Output: dict_values(['John', 31, 'Male'])
# Iterating through key-value pairs
for key, value in my_dict.items():
print(f"{key}: {value}")
# Creating a dictionary using the dict() constructor
another_dict = dict(name='Jane', age=25, city='San Francisco')
print(another_dict) # Output: {'name': 'Jane', 'age': 25, 'city': 'San Francisco'}