Open In App

Append a Key to a Python Dictionary

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Dictionaries are dynamic structures that allow us to add new key-value pairs to store additional information. For example, if we have a dictionary containing a student’s details and want to add a new field for their grade, we can easily append a key to the dictionary. Let's explores various ways to append a key to a dictionary.

Using Direct Assignment

This is the simplest and most efficient way to append a key to a dictionary. We directly assign a value to the new key using the assignment operator.

Python
# Initialize a dictionary
d = {"name": "Ak", "age": 25}

# Append a new key-value pair
d["grade"] = "A"

print(d)

Explanation:

  • A new key "grade" is added to the dictionary with the value "A".
  • This method is efficient as it directly modifies the dictionary in-place without any overhead.

Let's explore some more ways and see how we append a key to a dictionary in Python.

Using update()

update() method is useful when we want to add multiple key-value pairs at once.

Python
# Initialize a dictionary
d = {"name": "Ak", "age": 25}

# Append a new key using update
d.update({"grade": "A"})

print(d)

Explanation:

  • update() method accepts another dictionary as input and merges it with the existing one.
  • While slightly less efficient than direct assignment for a single key, it is preferred when adding multiple keys.

Using setdefault()

setdefault() method adds a key to the dictionary if it doesn’t already exist.

Python
# Initialize a dictionary
d = {"name": "Alice", "age": 25}

# Append a new key using setdefault
d.setdefault("grade", "A")

print(d)

Explanation:

  • The method checks if the key exists. If not, it adds the key with the provided value.
  • This is slightly less efficient than direct assignment but useful when we want to avoid overwriting an existing key.

Using Dictionary Unpacking

We can use dictionary unpacking with {**d, "key": "value"} to create a new dictionary with the appended key.

Python
# Initialize a dictionary
d = {"name": "Alice", "age": 25}

# Append a new key using dictionary unpacking
d = {**d, "grade": "A"}

print(d)

Explanation:

  • This creates a new dictionary by unpacking the existing one and adding the new key-value pair.
  • It is less efficient than in-place modification as it creates a copy of the dictionary.

Using for Loop (for Special Cases)

A for loop can be used to append keys dynamically based on conditions.

Python
# Initialize a dictionary
d = {"name": "Alice", "age": 25}

# Dynamically append a key using a loop
for key, value in [("grade", "A")]:
    d[key] = value

print(d)

Explanation:

  • This approach is useful when adding multiple keys dynamically.
  • However, it is less efficient than direct assignment for adding a single key.

Next Article
Practice Tags :

Similar Reads