To add a key-value pair to a dictionary in Python, you can use the dictionary's key assignment or the `update` method.
We can add a key-value pair to a dictionary in Python using key assignment. This example demonstrates how to add key-value pairs to a dictionary and print its contents.
For example,
my_dict
.my_dict = {}
# Add key-value pairs to the dictionary
my_dict[1] = 'One'
my_dict[2] = 'Two'
my_dict[3] = 'Three'
# Print the dictionary contents
print('Dictionary contents:')
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
Dictionary contents: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can add multiple key-value pairs to a dictionary in Python using the `update` method. This example demonstrates how to add key-value pairs to a dictionary using the `update` method and print its contents.
For example,
my_dict
.my_dict = {}
# Add key-value pairs to the dictionary using the update method
my_dict.update({
'A': 1.1,
'B': 2.2,
'C': 3.3
})
# Print the dictionary contents
print('Dictionary contents:')
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
Dictionary contents: Key: A, Value: 1.1 Key: B, Value: 2.2 Key: C, Value: 3.3
In this tutorial, we learned How to Add a Key-Value Pair to a Dictionary in Python language with well detailed examples.