VMware ESXi and vSphere Cluster Management

How to Add a New Key-Value Pair to a Python Dictionary

Learn how to add key-value pairs to Python dictionaries with square-bracket assignment, update existing values, use update(), and avoid common errors.

A Python dictionary, also called a dict, is a mutable mapping of unique keys to associated values. A key identifies an entry, while its value stores the related data.

Dictionary Syntax

You create a dictionary with curly braces. Each key is followed by a colon and its value. Multiple key-value pairs are separated by commas.

person = {'eye_color': 'blue', 'height': '165cm', 'weight': '53kg'}

In this example, 'eye_color' is a key and 'blue' is its value. String keys and values are common, but values can also be integers, lists, other dictionaries, or other Python objects.

Add a New Key-Value Pair

Use square-bracket assignment to add an entry:

dictionary[new_key] = value

For example:

person = {'eye_color': 'blue', 'height': '165cm', 'weight': '53kg'}
person['age'] = 22

print(person['age'])
print(person)

Because 'age' was not already a key in person, the assignment creates a new key-value pair. The output includes 22, and the dictionary now contains the added entry.

Dictionaries are mutable. This means assignment changes the original dictionary in place rather than creating a separate modified copy.

Adding a String-Valued Entry

A key can be associated with a string value just as it can with an integer:

person = {'name': 'Ava'}
person['city'] = 'Paris'

print(person['city'])

The key is 'city', and its value is 'Paris'. Retrieve a dictionary value by placing its key inside square brackets.

Adding Versus Updating an Entry

The same assignment syntax performs two different actions:

OperationExample patternResult

New key assignmentdata['new_key'] = value — Creates a new key-value pair.

Existing key assignmentdata['existing_key'] = value — Replaces the key's current value.

Bulk addition or updatedata.update({...}) — Adds missing keys and replaces matching keys.

If the key already exists, assignment does not create a second entry. It overwrites the previous value:

person = {'age': 22}
person['age'] = 23

print(person)
print(person['age'])

The dictionary still has one 'age' key, but its value is now 23. Dictionary keys must be unique. Assigning the same key again always replaces its prior value.

Add Several Entries with update()

For multiple entries, use the update() method. It accepts another dictionary or keyword arguments.

person = {'name': 'Ava'}
person.update({'age': 22, 'city': 'Paris'})

print(person)

This adds both 'age' and 'city'. If update() receives a key that already exists, that key's value is replaced.

person = {'name': 'Ava', 'city': 'London'}
person.update(city='Paris', age=22)

print(person)

Here, 'city' is updated and 'age' is added.

Dictionary Keys and Hashability

A dictionary key must be hashable, meaning Python can calculate a stable hash for it. Common valid keys include strings, integers, and tuples containing only immutable, hashable values.

data = {}
data['name'] = 'Ava'
data[7] = 'seven'
data[(2026, 'June')] = 'date'

Mutable objects such as lists and dictionaries cannot be keys:

data = {}
data[['a', 'b']] = 'letters'  # TypeError

Use a string, number, or suitable tuple instead.

Insertion Order

Python 3.7 and later preserve dictionary insertion order as a language guarantee. When you iterate over a dictionary or print it, entries appear in the order they were inserted. This order is not automatically sorted.

scores = {}
scores['first'] = 10
scores['second'] = 20
scores['third'] = 30

for key in scores:
    print(key)

The keys are printed as first, second, and third in Python 3.7+. In earlier Python versions, dictionary order was not guaranteed as a language feature.

Insertion order does not change how lookup works. scores['second'] finds the value by its key, regardless of where that key appears in the display order.

Common Syntax Pitfalls

Use straight quotation marks

Python requires ordinary straight single or double quotes for string literals. Do not copy typographic or curly quotation marks into code.

person['age'] = 22
person["city"] = "Paris"

Curly quotation marks such as ‘age’ or “city” can cause a SyntaxError.

Use the assignment operator

Use one equals sign when adding or changing a value:

person['age'] = 22

Do not confuse assignment with comparison, which uses ==.

Match the key exactly

Keys are case-sensitive. 'City', 'city', and 'CITY' are different keys.

Troubleshooting

  • A new entry replaces another value: The assigned key already exists. Use a distinct key if a separate entry is intended.
  • SyntaxError: Check for curly quotation marks, missing colons, or missing brackets. Use plain quotes such as 'age' or "age".
  • TypeError: unhashable type: A mutable list or dictionary was used as a key. Replace it with a string, integer, or appropriate tuple.
  • KeyError while reading: The key may not have been added, may be misspelled, or may use different capitalization. Test with if 'age' in person or use person.get('age') when a missing value should be handled safely.
  • Unexpected order: Older Python environments did not guarantee insertion order. Do not depend on dictionary order there when order is important.

Summary

  • A dictionary maps unique keys to values.
  • Add an entry with dictionary[new_key] = value.
  • If the key is new, assignment creates a key-value pair.
  • If the key already exists, assignment overwrites its value.
  • Dictionaries are mutable, so the original object changes in place.
  • Use update() to add or update several entries.
  • Keys must be hashable, and Python 3.7+ dictionaries preserve insertion order.