Add a New Key-Value Pair to a Dictionary in Python
Learn how to add a new key-value pair to an existing Python dictionary with bracket assignment, read the value, and avoid common key errors.
A dictionary is a mutable Python collection that maps unique keys to associated values. A key-value pair is one mapping entry: the key identifies the data, and the value is the data stored under that key.
Dictionaries use curly braces in literal syntax:
person = {'name': 'Mina', 'age': 22}
Here, 'name' and 'age' are keys. 'Mina' and 22 are their values. A dictionary is mutable, which means it can be changed after creation by adding, updating, or removing entries.
Keys must be unique. If you assign a value to a key that already exists, Python changes that key's value instead of creating a duplicate key.
Add One New Key-Value Pair
Use bracket assignment to add one known key and its value:
dictionary[new_key] = value
If new_key is not already in the dictionary, this expression creates a new key-value pair. You can then read the value by using the same key:
dictionary[new_key]
For example:
settings = {'theme': 'light'}
settings['font_size'] = 16
print(settings['font_size'])
print(settings)
Output:
16
{'theme': 'light', 'font_size': 16}
The exact display formatting can vary, but the dictionary contains both the original 'theme' pair and the new 'font_size' pair.
Worked Example: Adding an Age
Suppose a dictionary already stores personal attributes such as eye color, height, and weight. Add an 'age' key with an integer value:
person = {
'eye_color': 'blue',
'height': '165cm',
'weight': '53kg'
}
person['age'] = 22
print(person['age'])
print(person)
The first print() displays:
22
Conceptually, the dictionary now contains this additional pair:
'age': 22
Its complete contents are equivalent to:
{
'eye_color': 'blue',
'height': '165cm',
'weight': '53kg',
'age': 22
}
Adding Different Value Types
Dictionary values can be objects of many Python types. The key determines how you access the entry; the value can be a string, integer, boolean, list, another dictionary, or another suitable object.
profile = {}
profile['name'] = 'Mina' # string
profile['score'] = 95 # integer
profile['active'] = True # boolean
profile['tags'] = ['python', 'beginner'] # list
profile['address'] = {'city': 'Leeds'} # nested dictionary
print(profile)
This creates entries whose values have different types:
'name'maps to a string.'score'maps to an integer.'active'maps to a boolean.'tags'maps to a list.'address'maps to a nested dictionary.
Choose a Valid Dictionary Key
A dictionary key must be hashable. A hashable object has a stable hash value, so Python can efficiently locate its associated value. Common key types include strings, integers, and tuples containing only immutable, hashable items.
| Candidate key type | Can be used as a key? | Reason |
|---|---|---|
| String | Yes | Strings are hashable. |
| Integer | Yes | Integers are hashable. |
| Tuple of immutable values | Yes | The tuple is hashable when all of its contents are hashable. |
| List | No | Lists are mutable and unhashable. |
| Dictionary | No | Dictionaries are mutable and unhashable. |
| Set | No | Sets are mutable and unhashable. |
Valid examples include:
data = {}
data['language'] = 'Python'
data[1] = 'first item'
data[('x', 'y')] = 'coordinate'
A list cannot be used as a key:
data[['x', 'y']] = 'coordinate' # TypeError: unhashable type: 'list'
Adding Versus Modifying an Entry
The same bracket-assignment syntax handles both operations:
| Operation | Syntax | Behavior |
|---|---|---|
| Add a new key | my_dict['new_key'] = new_value | Creates an entry when the key is missing. |
| Update an existing key | my_dict['key'] = new_value | Replaces the value associated with an existing key. |
Add multiple entries with update() | my_dict.update({'a': 1, 'b': 2}) | Adds several entries and overwrites matching keys. |
| Read a value by key | value = my_dict['key'] | Retrieves the value; raises KeyError if the key is missing. |
For example, this does not add a second 'quantity' key. It modifies the existing value:
item = {'quantity': 1}
item['quantity'] = 2
print(item)
Output:
{'quantity': 2}
When you need to change an existing dictionary value, use the same assignment form deliberately. Keep the two tasks separate in your thinking: a missing key is added, while an existing key is updated.
Dictionary Insertion Order
Python 3.7 and later guarantee that dictionaries preserve insertion order, meaning entries are returned in the sequence in which they were added.
| Python version range | Ordering behavior |
|---|---|
| Python 3.7 and later | Insertion order is a language guarantee. |
| Python versions before 3.7 | Treat dictionaries as unordered; do not rely on insertion order. |
Order preservation does not change key-based access. Python still finds a value by its key, not by its position. It also is not the same as sorting: adding entries in order does not automatically arrange keys alphabetically or numerically.
Add Several Pairs with update()
Bracket assignment is the clearest choice for one known key-value pair. To add or merge several pairs, use update() with another dictionary or an iterable of key-value pairs:
user = {'name': 'Ari'}
user.update({'role': 'editor', 'verified': True})
print(user)
Result:
{'name': 'Ari', 'role': 'editor', 'verified': True}
update() also overwrites values for keys that already exist:
user.update({'role': 'admin'})
print(user['role']) # admin
An iterable of pairs also works:
user.update([('language', 'Python'), ('level', 'beginner')])
Troubleshooting
An entry replaces an existing value
The chosen key already exists. Use a distinct key if you want another entry, or keep the assignment if updating the existing value is intentional.
TypeError: unhashable type
A mutable object, such as a list or dictionary, was used as a key. Replace it with a string, integer, or appropriate immutable tuple.
KeyError while reading the new value
The key may not have been added, may be misspelled, or may differ in letter case. For example, 'Age' and 'age' are different keys. Check the exact spelling and add the entry before reading it.
If a missing key is expected and should not raise an exception, use get():
age = person.get('age')
print(age)
Dictionary order differs between environments
The code may be running on Python before 3.7, where insertion order was not guaranteed. Do not rely on dictionary order in those versions.
Curly quotation marks cause a syntax error
Python requires straight single or double quotation marks. Replace typographic quotation marks such as ‘name’ with 'name'.
Quick Reference
# Add one pair
my_dict['new_key'] = new_value
# Read the added value
value = my_dict['new_key']
# Inspect the complete dictionary
print(my_dict)
# Add or update several pairs
my_dict.update({'key_one': value_one, 'key_two': value_two})
For background, see What Are Dictionaries, What Are Lists, and Run Python Code.