Python online course

What Are Dictionaries in Python?

Learn how Python dictionaries store key-value pairs, create and access entries, update values, handle missing keys, and inspect dictionary contents.

What Is a Python Dictionary?

A dictionary is a mutable Python mapping that stores associations between unique keys and their corresponding values. A mapping lets you find data by an identifier instead of by a numeric position.

For example, a person dictionary can associate the key 'eye_color' with the value 'blue'. The association between one key and one value is called a key-value pair, or an item.

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

Dictionaries are useful for organizing related information, such as a person's attributes, application settings, product details, or user preferences.

  • Dictionary: A mutable Python mapping of keys to values.
  • Mapping: A collection that maps each key to a corresponding value.
  • Key: A unique identifier used to find a value.
  • Value: The data associated with a key.
  • Key-value pair: One association stored in a dictionary.
  • Item: Another name for a key-value pair.
  • Mutable: Able to be changed after creation.

Dictionary Syntax

Dictionaries are written with curly braces, {}. Each key is followed by a colon, and the value follows the colon. Commas separate multiple items.

settings = {
    'theme': 'dark',
    'font_size': 14,
    'notifications': True
}
ComponentMeaningExample
Curly bracesMark the beginning and end of a dictionary{...}
KeyIdentifies the value'theme'
ColonSeparates a key from its value'theme': 'dark'
ValueData associated with the key'dark'
CommaSeparates items'dark', 'font_size'

The empty dictionary is written as {}:

empty_data = {}

Keys and Values

Keys must be unique

A key identifies exactly one current value in a dictionary. The same key cannot represent two separate entries. If a dictionary literal repeats a key, the later value replaces the earlier one.

scores = {'Mina': 80, 'Mina': 92}
print(scores)  # {'Mina': 92}

Use distinct keys when entries must remain separate. If one key should contain several related values, store a list or another dictionary as its value.

Keys must be hashable

A dictionary key must be hashable. An object is hashable when it can provide a stable hash value, allowing Python to locate it efficiently in a dictionary. Common hashable keys include strings, integers, and tuples containing only immutable hashable values.

TypeCan Be a Key?Reason
strYesStrings are immutable and hashable.
intYesIntegers are immutable and hashable.
Tuple of immutable valuesYesThe tuple is hashable when all of its contents are hashable.
listNoLists are mutable and unhashable.
dictNoDictionaries are mutable and unhashable.
locations = {
    'home': 'North',
    1: 'first item',
    ('x', 'y'): 'a coordinate'
}

Values have fewer restrictions. They may be strings, numbers, booleans, lists, dictionaries, custom objects, or nearly any other Python type.

student = {
    'name': 'Mina',
    'score': 92,
    'subjects': ['Python', 'Math'],
    'active': True,
    'contact': {'email': 'mina@example.test'}
}

Creating Dictionaries

Using a dictionary literal

The most common approach is a dictionary literal: write keys and values inside curly braces.

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

Creating an empty dictionary

Create an empty dictionary when the entries will be collected or calculated later, then assign values using keys.

person = {}
person['name'] = 'Mina'
person['age'] = 25

Using dict()

dict is both the built-in dictionary type and a constructor that creates dictionaries. Keyword arguments are convenient when the keys are valid Python identifier names.

settings = dict(theme='dark', font_size=14)
print(settings)  # {'theme': 'dark', 'font_size': 14}

For keys that contain spaces or punctuation, use a dictionary literal or pass key-value pairs explicitly.

person = dict([('eye_color', 'blue'), ('age', 25)])

Accessing Values by Key

Use square brackets with a key to retrieve its value. This is key lookup, not positional indexing.

person = {'eye_color': 'blue', 'height': '165cm', 'weight': '53kg'}
print(person['eye_color'])  # blue

Square-bracket lookup is appropriate when the key must exist. If the key is absent, Python raises a KeyError, the exception raised for a missing key.

print(person['nickname'])
# KeyError: 'nickname'

Using get() for safer lookup

The get() method returns the value when the key exists. When it does not exist, get() returns None by default instead of raising KeyError. You can provide an optional default value.

nickname = person.get('nickname', 'Not provided')
print(nickname)  # Not provided

weight = person.get('weight')
print(weight)  # 165cm

Adding and Changing Entries

Dictionaries are mutable, so you can change them after creation. Assigning to a key has two possible effects:

  • If the key is new, Python adds a new key-value pair.
  • If the key already exists, Python replaces its previous value.
person = {'eye_color': 'blue', 'height': '165cm', 'weight': '53kg'}

# Add a new key-value pair
person['age'] = 25

# Update an existing value
person['height'] = '170cm'

print(person)

After the assignments, 'age' is a new item and the old height value has been replaced. The dictionary itself has been modified; no separate dictionary is required.

GoalSyntaxResult or Note
Create a dictionarydata = {'a': 1}Creates a mapping with one item.
Read a valuedata['a']Raises KeyError if the key is absent.
Safely read a valuedata.get('a', default)Returns the default when the key is absent.
Add a key-value pairdata['b'] = 2Adds a new item when 'b' is new.
Update a valuedata['a'] = 3Replaces the value for an existing key.
Check whether a key exists'a' in dataReturns True or False.
View keys, values, and itemsdata.keys(), data.values(), data.items()Returns views of the dictionary contents.

Dictionary Ordering and Access

Modern Python dictionaries preserve insertion order. This means iteration and display generally follow the order in which keys were added. Updating an existing key changes its value but does not turn the dictionary into a list.

Dictionaries are accessed by keys rather than numeric positions. This does not retrieve the first item:

data = {'first': 'A', 'second': 'B'}
print(data[0])  # KeyError: 0

Use the actual key instead:

print(data['first'])  # A

If positional handling is genuinely needed, you can deliberately convert keys or items to a list, but ordinary dictionary lookup should use meaningful keys.

Inspecting Dictionary Contents

Keys, values, and items

The keys(), values(), and items() methods return view objects that reflect the dictionary's contents.

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

print(person.keys())
print(person.values())
print(person.items())
  • keys() provides the dictionary's keys.
  • values() provides the dictionary's values.
  • items() provides key-value pairs, commonly represented as two-element tuples.

Testing for a key with in

Use the in operator to test whether a key is present. This is useful before square-bracket lookup when missing data needs special handling.

if 'weight' in person:
    print(person['weight'])

For dictionaries, in checks keys by default, not values.

Counting items with len()

len() returns the number of stored key-value pairs.

print(len(person))  # 3

Common Beginner Errors

Forgetting quotes around a string key

A quoted string is a literal key. Without quotes, Python treats the word as a variable name.

person = {'eye_color': 'blue'}
print(person[eye_color])       # Error if eye_color is not a variable
print(person['eye_color'])     # Correct

Looking up a missing key

Square brackets raise KeyError when the requested key is not present. Check with in or use get() when absence is expected.

if 'nickname' in person:
    print(person['nickname'])

print(person.get('nickname', 'Not provided'))

Using a mutable object as a key

Lists and dictionaries cannot be keys because they are mutable and unhashable.

bad_data = {[1, 2]: 'numbers'}  # TypeError: unhashable type: 'list'

Use a hashable alternative such as a tuple when its contents are immutable.

good_data = {(1, 2): 'coordinates'}

Expecting duplicate keys to create separate entries

Keys are unique. A later assignment to the same key replaces the earlier value.

data = {'status': 'draft', 'status': 'published'}
print(data)  # {'status': 'published'}

Use different keys or make the value a list when multiple values belong to one category.

data = {'statuses': ['draft', 'published']}

Confusing dictionary lookup with list indexing

A list uses numeric positions such as items[0]. A dictionary uses keys such as person['height'], even when its keys are integers.

Troubleshooting Dictionary Problems

  • KeyError during lookup: The key may be absent, misspelled, or differently capitalized. Inspect keys(), test with in, or use get().
  • TypeError: unhashable type: A list or dictionary was used as a key. Replace it with a string, integer, or suitable tuple.
  • An entry seems to disappear: The dictionary received the same key more than once. The later value replaced the earlier value.
  • A string key produces an unexpected error: Add quotes around the literal key, for example person['eye_color'].
  • Numeric indexing fails: Dictionaries are not accessed by item position. Use the relevant key.

Complete Example

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

print(person['eye_color'])

person['age'] = 25
person['weight'] = '60kg'

print(person.get('nickname', 'Not provided'))
print(person.keys())
print(person.values())
print(person.items())

if 'weight' in person:
    print('Weight:', person['weight'])

This example creates a dictionary, reads a value, adds an attribute, updates an existing attribute, safely checks optional information, inspects its views, and tests whether a key exists.

Key Points to Remember

  • A dictionary maps unique keys to values.
  • Dictionary literals use curly braces, colons, and commas.
  • Keys must be unique and hashable; values can be almost any Python type.
  • Use square brackets for required keys and get() for optional keys.
  • Assignment adds a new key or replaces the value of an existing key.
  • Dictionaries are mutable and preserve insertion order in modern Python.
  • Use keys(), values(), items(), in, and len() to inspect contents.
  • Do not treat a dictionary like a list: look up values by key, not numeric position.

For related collection concepts, see what Python lists are and Python tuples if available in your course materials. To continue with dictionary-specific practice, explore adding a new key-value pair and looping through a dictionary.