Skip to Content
Nextra 4.0 is released 🎉

Modifying Dictionaries

Changing a value

To update a value, use square brackets with the key and assign a new value:

person = {"name": "Alice", "age": 30, "city": "New York"} person["age"] = 31 print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}

Adding a new key-value pair

Adding a new key works exactly the same way — if the key doesn’t exist yet, Python creates it:

person["occupation"] = "Engineer" print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}

Removing a key-value pair

You have two options for removing a pair:

del — removes the key-value pair directly:

del person["city"] print(person) # Output: {'name': 'Alice', 'age': 31, 'occupation': 'Engineer'}

pop() — removes the pair and gives back the value, so you can use it:

occupation = person.pop("occupation") print(occupation) # Output: Engineer print(person) # Output: {'name': 'Alice', 'age': 31}

Use del when you just want to remove something. Use pop() when you need the value before it’s gone.

Looping over a dictionary

Use .items() to loop over both keys and values at the same time:

person = {"name": "Alice", "age": 31, "city": "New York"} for key, value in person.items(): print(key, "->", value) # Output: # name -> Alice # age -> 31 # city -> New York

You can also loop over just the keys or just the values:

for key in person: print(key) # name, age, city for value in person.values(): print(value) # Alice, 31, New York

Example: Color palette

Dictionaries are a natural fit for storing named colors — something you’ll do in the Generative Art project:

palette = { "background": (15, 15, 30), "primary": (255, 100, 80), "secondary": (80, 180, 255), "accent": (255, 220, 50), } # Access a color by name print(palette["primary"]) # (255, 100, 80) # Loop to print all colors for name, color in palette.items(): print(f"{name}: {color}")

Try it out

main.py
Output
Last updated on