How to add new keys to a dictionary in Python?

To add new keys to a dictionary in Python, you can use several straightforward methods. Here’s a step-by-step guide with examples:

1. Using Square Bracket Assignment

Add or update a key-value pair by directly assigning a value to a new key:

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

# Add a new key-value pair
my_dict["c"] = 3
print(my_dict)  # Output: {"a": 1, "b": 2, "c": 3}

# Update an existing key
my_dict["a"] = 100
print(my_dict)  # Output: {"a": 100, "b": 2, "c": 3}

2. Using the update() Method

Add multiple key-value pairs at once (or merge another dictionary):

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

# Add multiple keys using a dictionary
my_dict.update({"c": 3, "d": 4})
print(my_dict)  # Output: {"a": 1, "b": 2, "c": 3, "d": 4}

# Add keys using keyword arguments
my_dict.update(e=5, f=6)
print(my_dict)  # Output: {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}

3. Using Dictionary Unpacking (Python 3.5+)

Merge dictionaries into a new dictionary (does not modify the original):

original = {"a": 1, "b": 2}
new_dict = {**original, "c": 3, "d": 4}
print(new_dict)  # Output: {"a": 1, "b": 2, "c": 3, "d": 4}

4. Using setdefault()

Add a key with a default value only if it doesn’t already exist:

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

# Add a new key with a default value
my_dict.setdefault("c", 3)
print(my_dict)  # Output: {"a": 1, "b": 2, "c": 3}

# Existing keys are NOT overwritten
my_dict.setdefault("a", 100)
print(my_dict)  # Output: {"a": 1, "b": 2, "c": 3} (unchanged)

Key Notes

  • Keys must be hashable (e.g., strings, numbers, tuples). Mutable types like lists cannot be keys.
  • Use update() for bulk additions and my_dict[key] = value for single keys.
  • setdefault() is useful for initializing keys with default values safely.

Example: Adding Nested Keys

my_dict = {"user": {"name": "Alice"}}

# Add a nested key
my_dict["user"]["age"] = 30
print(my_dict)  # Output: {"user": {"name": "Alice", "age": 30}}

Common Mistakes

  • Overwriting Existing Keys:
    Assigning to an existing key replaces its value. Check existence first if needed:
  if "key" not in my_dict:
      my_dict["key"] = "value"
  • Using Mutable Keys:
    This will throw an error:
  my_dict[[1, 2]] = "list_as_key"  # TypeError: unhashable type: 'list'

Summary

MethodUse Case
my_dict[key]Add/update single keys
update()Add multiple keys or merge dictionaries
{**dict}Create a new merged dictionary (no mutation)
setdefault()Safely initialize keys with defaults

Choose the method that best fits your needs!

Leave a Reply

Your email address will not be published. Required fields are marked *