How to add new keys to a dictionary in python?

0
0

In Python, you can add new keys to a dictionary by assigning a value to a new key or an existing key that does not exist. Here’s an example:

# Create a dictionary with some initial key-value pairs
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}

# Add a new key-value pair to the dictionary
my_dict[‘key3’] = ‘value3’

# Print the updated dictionary
print(my_dict)

In this example, a new key-value pair 'key3': 'value3' is added to the dictionary by assigning a value to a new key 'key3'. The updated dictionary is printed to the console, which will output:

{‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

If the key already exists in the dictionary, the value associated with that key will be overwritten:

# Update the value of an existing key in the dictionary
my_dict[‘key2’] = ‘new_value2’

# Print the updated dictionary
print(my_dict)

In this example, the value of the existing key 'key2' is updated to 'new_value2'. The updated dictionary is printed to the console, which will output:

{‘key1’: ‘value1’, ‘key2’: ‘new_value2’, ‘key3’: ‘value3’}

So, whether you want to add a new key or update an existing key, you can use the same syntax to assign a value to the dictionary using the key as the index.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.