what happens if you try to add a new key to a dictionary that already exists?

2 hours ago 1
Nature

If you try to add a new key to a dictionary that already exists in Python, the behavior depends on whether the key is already present in the dictionary or not:

  • If the key does not exist:
    The new key-value pair is added to the dictionary.

  • If the key already exists:
    The existing key's value is updated (overwritten) with the new value you provide.

Example:

python

my_dict = {'a': 1, 'b': 2}

# Adding a new key
my_dict['c'] = 3
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

# Adding a key that already exists (updates value)
my_dict['a'] = 10
print(my_dict)  # Output: {'a': 10, 'b': 2, 'c': 3}

Summary:

  • Adding a new key adds a new entry.
  • Adding an existing key updates its value.

Let me know if you'd like to see how this works in other programming languages or more examples!