CodeGym /Java Course /Python SELF EN /Modifying Dictionaries

Modifying Dictionaries

Python SELF EN
Level 11 , Lesson 5
Available

5.1 Adding Elements

We've already learned how to work with dictionary items, now let's dive into how to quickly and easily modify the dictionary itself. As usual, we'll start with adding elements.

Adding a Single Element

To add a new item to a dictionary you can use square brackets []. If the key already exists, its value will be updated.


person = {"name": "Alice", "age": 25}

# Add a new element to the dictionary
person["city"] = "New York"

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Adding an Element if the Key is Missing

Sometimes you need to add an item only if the key isn't already in the dictionary. This can be done using a conditional statement.


person = {"name": "Alice", "age": 25}

# Add the element only if the key is missing
if "city" not in person:
    person["city"] = "New York"

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Adding Multiple Elements Using the update() Method

The update() method allows you to add multiple key-value pairs at once. You can pass another dictionary or an iterable holding key-value pairs.


person = {"name": "Alice", "age": 25}
updates = {"city": "New York", "country": "USA"}

# Update the dictionary with new elements
person.update(updates)

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}

You can also use named arguments:


person = {"name": "Alice", "age": 25}

# Use named arguments to add items
person.update(city="New York", country="USA")

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}

5.2 Modifying Elements

Modifying elements works the same way as adding them, but if the key already had an old value, it will be replaced with the new one.

Updating the Value by Key

You can update a value in a dictionary by simply assigning a new value to an existing key.


person = {"name": "Alice", "age": 25, "city": "New York"}

# Update the value by key
person["age"] = 26

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}

Using the setdefault() Method

The setdefault() method returns the value for a specified key. If the key is missing, it adds it to the dictionary with a specified default value.


person = {"name": "Alice", "age": 25}

# Use setdefault to add an item
city = person.setdefault("city", "New York")

# Print the city value
print(city)  # Output: New York

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Updating Elements using the update() Method

You can use the update() method to update the values of items in the dictionary using another dictionary or an iterable.


person = {"name": "Alice", "age": 25}
updates = {"age": 30, "city": "New York"}

# Update the dictionary using update()
person.update(updates)

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

5.3 Removing Dictionary Elements

You can remove elements from a dictionary in several ways:

Removing an Element Using the del Operator

The del operator removes a key-value pair from the dictionary by the specified key.


person = {"name": "Alice", "age": 25, "city": "New York"}

# Remove the element by key
del person["age"]

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'city': 'New York'}

Removing an Element Using the pop(key, def_value) Method

The pop() method removes the element with the specified key and returns its value. If the key is missing, you can specify a default value to avoid an error.


person = {"name": "Alice", "age": 25, "city": "New York"}

# Remove the element and get its value
age = person.pop("age")

# Print the removed value
print(age)  # Output: 25

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'city': 'New York'}

Removing the Last Added Element Using the popitem() Method

The popitem() method removes and returns the last added key-value pair. It's especially useful in older Python versions for working with unordered dictionaries.


person = {"name": "Alice", "age": 25, "city": "New York"}

# Remove and get the last added key-value pair
last_item = person.popitem()

# Print the removed pair
print(last_item)  # Output: ('city', 'New York')

# Print the updated dictionary
print(person)  # Output: {'name': 'Alice', 'age': 25}

Clearing a Dictionary Using the clear() Method

The clear() method removes all elements from the dictionary, leaving it empty.


person = {"name": "Alice", "age": 25, "city": "New York"}

# Clear the dictionary
person.clear()

# Print the cleared dictionary
print(person)  # Output: {}
2
Task
Python SELF EN, level 11, lesson 5
Locked
A student - it sounds proud.
A student - it sounds proud.
2
Task
Python SELF EN, level 11, lesson 5
Locked
Editor.
Editor.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION