Dictionaries:
Dictionaries in Python
In Python, dictionaries are a built-in data type that allows you to store collections of key-value pairs. Dictionaries are mutable, meaning you can change their contents after they are created.
Creating Dictionaries
There are several ways to create dictionaries in Python:
Using curly braces {}
my_dict = {'key1': 'value1', 'key2': 'value2'}
Using the dict()
constructor
my_dict = dict(key1='value1', key2='value2')
Using a list of tuples
my_dict = dict([('key1', 'value1'), ('key2', 'value2')])
Using a list of lists
my_dict = dict([['key1', 'value1'], ['key2', 'value2']])
Using the zip()
function
keys = ['key1', 'key2']
values = ['value1', 'value2']
my_dict = dict(zip(keys, values))
Major Operations on Dictionaries
Accessing Values
value = my_dict['key1']
Adding or Updating Values
my_dict['key3'] = 'value3'
my_dict['key1'] = 'new_value1'
Deleting Key-Value Pairs
del my_dict['key1']
Checking for Keys
if 'key1' in my_dict:
print("Key exists")
Iterating Through Keys and Values
for key, value in my_dict.items():
print(key, value)
Getting Keys and Values Separately
keys = my_dict.keys()
values = my_dict.values()
Copying a Dictionary
new_dict = my_dict.copy()
Merging Dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
Using Default Values
value = my_dict.get('nonexistent_key', 'default_value')
Removing and Returning a Key-Value Pair
value = my_dict.pop('key1', 'default_value')
Clearing All Key-Value Pairs
my_dict.clear()
Example Usage
# Creating a dictionary
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
# Accessing values
print(person['name']) # Alice
# Adding a new key-value pair
person['email'] = 'alice@example.com'
# Updating an existing value
person['age'] = 31
# Deleting a key-value pair
del person['city']
# Iterating through the dictionary
for key, value in person.items():
print(f"{key}: {value}")
# Checking for a key
if 'name' in person:
print("Name exists in the dictionary")