0
0
Pythonprogramming~5 mins

Adding and updating key-value pairs in Python

Choose your learning style9 modes available
Introduction

We add or update key-value pairs to store or change information in a dictionary. This helps keep data organized and easy to find.

When you want to add a new contact name and phone number to your phone book.
When you need to update the price of an item in a shopping list.
When you want to store a student's grade and later change it if needed.
When you keep track of inventory and add new products or update quantities.
When you want to save settings and change them based on user preferences.
Syntax
Python
dictionary[key] = value

This syntax works for both adding new pairs and updating existing ones.

If the key exists, the value is updated. If not, a new pair is added.

Examples
Adds the key 'color' with value 'blue' to an empty dictionary.
Python
my_dict = {}
my_dict['color'] = 'blue'  # Adds a new key-value pair
Changes the value of the existing key 'color' from 'blue' to 'red'.
Python
my_dict = {'color': 'blue'}
my_dict['color'] = 'red'  # Updates the value for 'color'
Adds a new key 'name' with value 'Alice' alongside the existing 'age' key.
Python
my_dict = {'age': 25}
my_dict['name'] = 'Alice'  # Adds a new key 'name'
Sample Program

This program starts with a dictionary holding a name and age. It adds a city and updates the age. Finally, it prints the updated dictionary.

Python
person = {'name': 'John', 'age': 30}

# Add a new key-value pair
person['city'] = 'New York'

# Update an existing key's value
person['age'] = 31

print(person)
OutputSuccess
Important Notes

Using the same syntax for adding and updating keeps code simple and clear.

Keys must be unique; updating replaces the old value.

Values can be any data type, like numbers, strings, lists, or even other dictionaries.

Summary

Use dictionary[key] = value to add or update key-value pairs.

Adding creates a new pair if the key is not present.

Updating changes the value of an existing key.