Skip to content
PythonWorking with Collectionsbeginner18 min read

Dictionaries: Keys and Values

Learn to create dictionaries, access values using keys, add and update entries, handle missing keys with get(), and iterate through key-value pairs.

In this lesson, you will learn

  • ✓Explain how dictionaries store unique keys and their associated values.
  • ✓Create dictionaries and retrieve values using square-bracket key access.
  • ✓Add new entries, update existing values, and remove entries.
  • ✓Distinguish direct key access from get() when a key may be missing.
  • ✓Use in, keys(), values(), items(), and loops to inspect dictionary contents.
  • ✓Trace dictionary operations and predict exact program output.

1. Understanding dictionaries and key-value pairs

A dictionary, written using the built-in dict type, stores associations between keys and values. Each entry contains a key, a colon, and its corresponding value. Commas separate entries, and curly braces surround the dictionary.

Consider student = {'name': 'Asha', 'score': 90}. The key 'name' is associated with the string value 'Asha'. The key 'score' is associated with the integer value 90. The key tells Python which value you want to retrieve.

Keys must be unique within a dictionary. Values do not have to be unique, and values can be strings, numbers, lists, other dictionaries, or other Python objects. Dictionary keys must be hashable; common beginner-friendly key types include strings, integers, and suitable tuples.

Dictionaries are mutable, which means you can add entries, change values, and remove entries after creating one. Python dictionaries preserve insertion order, so iteration follows the order in which keys were inserted, except that updating an existing key does not move it to the end.

Use {} or dict() to create an empty dictionary. Remember that {} creates an empty dictionary, not an empty set; an empty set is created with set().

Create and read a dictionary

Create and read a dictionary
python
student = {'name': 'Asha', 'score': 90}
print(student)
print(student['name'])
print(student['score'])
Output
{'name': 'Asha', 'score': 90} Asha 90

The first statement creates a dictionary with two entries. The first print() displays the dictionary in insertion order. student['name'] retrieves the value associated with the key 'name'. student['score'] retrieves the integer associated with the key 'score'. Square brackets contain a key here, not a numeric list index.

Note

A dictionary maps keys to values. It is not a list: its primary lookup operation uses a key rather than a positional index.

2. Accessing values, adding entries, and updating values

Use dictionary[key] to retrieve the value associated with a key. For example, student['name'] retrieves the value stored under 'name'. If that key does not exist, direct access raises a KeyError.

Assignment with dictionary[key] = value has two possible effects. If the key is new, Python adds a new entry. If the key already exists, Python replaces its associated value. The same syntax handles both operations.

Changing a value does not create a second entry with the same key. A dictionary cannot contain two separate entries for the same key. If a key is assigned more than once, its most recently assigned value is the value that remains.

Use del dictionary[key] to remove an existing entry. Deleting a missing key raises KeyError, so check that the key exists first when its presence is uncertain.

Add a new key-value pair

Add a new key-value pair
python
user = {'name': 'Ari'}
user['active'] = True
user['age'] = 22
print(user)
Output
{'name': 'Ari', 'active': True, 'age': 22}

Initially, the dictionary contains only the key 'name'. The assignment to user['active'] adds a Boolean value. The assignment to user['age'] adds an integer value. Both new entries appear after the original entry because they were inserted later.

Caution

Direct access with student['grade'] raises KeyError if 'grade' is missing. Use get() or check membership with in when the key may not exist.

3. Safely reading values with get()

The get() method retrieves a value without raising KeyError when the requested key is missing. Its basic forms are dictionary.get(key) and dictionary.get(key, default).

If the key exists, get() returns its associated value. If the key is missing and you provide a default, get() returns that default. If you do not provide a default, it returns None.

For example, student.get('grade', 'N/A') returns 'N/A' if the dictionary does not contain 'grade'. This is useful when missing information is expected and the program should continue without an exception.

There is an important difference between a missing key and a key whose value is None. get() returns None in both cases if you do not supply a different default. If that distinction matters, use membership testing with in.

Use get() with a default value

Use get() with a default value
python
student = {'name': 'Asha', 'score': 90}
print(student.get('name'))
print(student.get('grade', 'N/A'))
print(student.get('city'))
Output
Asha N/A None

The key 'name' exists, so get() returns 'Asha'. The key 'grade' is missing, so get() returns the supplied default 'N/A'. The key 'city' is missing and no default was supplied, so get() returns None. print() displays None as the text None.

Note

get() does not insert a missing key into the dictionary. It only returns a value or a default.

4. Checking keys and inspecting dictionary contents

Use the in operator to check whether a key exists in a dictionary. The expression 'name' in student returns True if 'name' is a key in student and False otherwise. Use not in to check the opposite.

When you use in directly with a dictionary, Python checks its keys, not its values. For example, 90 in student checks whether 90 is a key; it does not check whether any entry has the value 90.

Three useful dictionary methods are keys(), values(), and items(). keys() provides a view of the keys, values() provides a view of the values, and items() provides a view of key-value pairs as tuples.

These methods return view objects rather than ordinary lists. You can iterate over the views directly or convert them to lists when a list is specifically needed. The views reflect changes to the underlying dictionary.

A for loop over a dictionary iterates over its keys by default. To process both keys and values together, use for key, value in dictionary.items(). This is often the clearest way to display or calculate with each entry.

Check whether keys exist

Check whether keys exist
python
student = {'name': 'Asha', 'score': 90}
print('name' in student)
print('grade' in student)
print(90 in student)
print(90 in student.values())
Output
True False False True

'name' is an existing key, so the first expression is True. 'grade' is not a key, so the second expression is False. The expression 90 in student checks keys. The integer 90 is not a key, so the result is False. student.values() exposes the dictionary's values, and 90 is one of them, so the last result is True.

Note

Use key in dictionary for key membership and value in dictionary.values() for value membership. They answer different questions.

5. A complete dry run: trace dictionary changes

A dry run means following a program statement by statement without skipping any operation. For a dictionary, track its current key-value pairs and notice whether each assignment adds an entry or replaces an existing value.

In the example below, the dictionary starts with two entries. The program adds a new key, updates an existing key, reads a missing key safely, and then prints the final dictionary.

Trace creation, update, and lookup

Trace creation, update, and lookup
python
student = {'name': 'Asha', 'score': 90}
student['grade'] = 'A'
student['score'] = 95
print(student.get('city', 'Unknown'))
print(student)
Output
Unknown {'name': 'Asha', 'score': 95, 'grade': 'A'}

Statement 1 creates a dictionary with name='Asha' and score=90. Statement 2 adds the new key 'grade' with the value 'A'. Statement 3 changes the existing 'score' value from 90 to 95. Its insertion position remains unchanged. Statement 4 looks for 'city'. Since the key is missing, get() returns 'Unknown' without modifying the dictionary. Statement 5 prints the final dictionary. Its key order is name, score, grade.

Note

The output of get() does not tell you that the dictionary was changed. In this example, the missing key 'city' is not added.

6. Practical use and common edge cases

Dictionaries are useful when information has named attributes. A product dictionary might store a product name, price, and stock count. A user dictionary might store a username and whether the account is active.

Choose meaningful keys that make your code easy to understand. If a key may be absent, decide whether to use get(), check with in, or handle the KeyError from direct access.

Remember that dictionary keys must be hashable. A list or another dictionary cannot be used directly as a key because these objects are mutable and unhashable. A tuple can be used as a key when all its elements are hashable.

A dictionary can contain a value of None, and None is different from the absence of a key. Use 'key' in dictionary when you need to know whether the key actually exists.

When deleting an entry, use del only when the key is known to exist or after checking membership. Alternatively, pop(key, default) can remove and return a value while supplying a fallback for a missing key.

Do not change a dictionary's size while iterating over it. If you need to remove selected entries, build a separate dictionary or collect the keys to remove first, then delete them after the iteration.

A practical product record

A practical product record
python
product = {'name': 'Notebook', 'price': 40, 'stock': 12}
product['stock'] = product['stock'] - 2
print(product['name'])
print(product['stock'])
print(product.get('discount', 0))
Output
Notebook 10 0

The dictionary stores the product name, price, and stock count. The stock value is reduced from 12 to 10 and assigned back to the existing key. The product name is retrieved using its key. No discount key exists, so get() returns the default value 0.

Caution

Do not use a list as a dictionary key. For example, data[[1, 2]] = 'value' raises TypeError because lists are unhashable. Use an appropriate immutable key, such as a tuple of hashable elements, when that matches the problem.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Using a value as though it were a key.

Why it happens: Dictionary lookup uses a key to retrieve its associated value; passing a value instead works only if that value happens to be an existing key.

Incorrect Approach
script.py
python
Using a value as though it were a key.
Correct Solution
script.py
python
Remember that dictionary[key] looks up an entry by key. To search values, use dictionary.values() or inspect dictionary.items().

Key takeaway: Remember that dictionary[key] looks up an entry by key. To search values, use dictionary.values() or inspect dictionary.items().

#2 Assuming dictionary keys behave like list indexes.

Why it happens: Dictionary keys are labels rather than positional indexes, so use the actual key or an explicit iteration position when needed.

Incorrect Approach
script.py
python
Assuming dictionary keys behave like list indexes.
Correct Solution
script.py
python
A dictionary is accessed by keys, such as student['name']. A key may be a string or number; it does not need to be a position in a sequence.

Key takeaway: A dictionary is accessed by keys, such as student['name']. A key may be a string or number; it does not need to be a position in a sequence.

#3 Accessing a missing key with square brackets.

Why it happens: Square-bracket access raises KeyError for a missing key; use get() or an explicit membership check when absence is expected.

Incorrect Approach
script.py
python
Accessing a missing key with square brackets.
Correct Solution
script.py
python
Use get() or check membership with in if the key may be missing. Direct access raises KeyError when the key is absent.

Key takeaway: Use get() or check membership with in if the key may be missing. Direct access raises KeyError when the key is absent.

#4 Thinking get() adds the default value to the dictionary.

Why it happens: get(key, default) returns the default when the key is absent but does not insert that default into the dictionary.

Incorrect Approach
script.py
python
Thinking get() adds the default value to the dictionary.
Correct Solution
script.py
python
get() returns a default value without inserting a new key-value pair.

Key takeaway: get() returns a default value without inserting a new key-value pair.

#5 Believing assigning the same key twice creates duplicate entries.

Why it happens: Dictionary keys are unique; assigning to an existing key updates its value rather than creating a duplicate entry.

Incorrect Approach
script.py
python
Believing assigning the same key twice creates duplicate entries.
Correct Solution
script.py
python
Assigning an existing key replaces its value. A dictionary has at most one entry for a given key.

Key takeaway: Assigning an existing key replaces its value. A dictionary has at most one entry for a given key.

#6 Using a mutable list or dictionary as a key.

Why it happens: Dictionary keys must be hashable, and mutable lists or dictionaries are unhashable and cannot be used as keys.

Incorrect Approach
script.py
python
Using a mutable list or dictionary as a key.
Correct Solution
script.py
python
Use a hashable key, such as a string, integer, or tuple containing only hashable elements.

Key takeaway: Use a hashable key, such as a string, integer, or tuple containing only hashable elements.

#7 Assuming in checks dictionary values.

Why it happens: The in operator checks dictionary keys by default; use values() to test values or items() to inspect key-value pairs.

Incorrect Approach
script.py
python
Assuming in checks dictionary values.
Correct Solution
script.py
python
key in dictionary checks keys. To test a value, use value in dictionary.values().

Key takeaway: key in dictionary checks keys. To test a value, use value in dictionary.values().

#8 Assuming updating a key moves it to the end.

Why it happens: Updating the value of an existing key generally preserves its insertion position; assigning a new key adds a new entry.

Incorrect Approach
script.py
python
Assuming updating a key moves it to the end.
Correct Solution
script.py
python
Updating an existing value preserves the key's insertion position. Deleting a key and inserting it again places it at the end.

Key takeaway: Updating an existing value preserves the key's insertion position. Deleting a key and inserting it again places it at the end.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a dictionary in Python, and how is it different from a list?
Answer:
A dictionary is a mutable mapping of unique keys to values. You normally retrieve a value using its key, such as student['name']. A list is an ordered sequence whose elements are commonly retrieved using integer indexes such as items[0]. Dictionaries are useful when data is naturally associated with named keys.
Q2:What is the difference between dictionary[key] and dictionary.get(key)?
Answer:
Both retrieve a value when the key exists. If the key is missing, dictionary[key] raises KeyError. dictionary.get(key) returns None by default, or it returns a supplied default such as dictionary.get(key, 0). get() does not insert the missing key.
Q3:How do you add or update a dictionary entry?
Answer:
Use dictionary[key] = value. If the key is absent, the assignment adds a new entry. If the key already exists, the assignment replaces its value.
Q4:How do you check whether a key exists in a dictionary?
Answer:
Use key in dictionary, which returns True if the key exists and False otherwise. Use key not in dictionary to test for absence. Membership testing with in checks keys, not values.
Q5:What do keys(), values(), and items() return?
Answer:
keys() provides a view of the keys, values() provides a view of the values, and items() provides a view of key-value pairs represented as tuples. These views can be iterated over and reflect changes to the underlying dictionary.
Q6:Can a list be used as a dictionary key? Why or why not?
Answer:
No. A list is mutable and unhashable, so it cannot be used as a dictionary key. Use a hashable object such as a string, integer, or tuple whose elements are all hashable.
Q7:What happens when the same key is assigned more than once?
Answer:
The most recent assignment replaces the value associated with that key. The dictionary does not gain a duplicate entry for the same key, and updating an existing key does not change its insertion position.

Key takeaways

  • A dictionary stores key-value pairs, and each key is unique within that dictionary.
  • Use dictionary[key] to retrieve a known key's value; a missing key raises KeyError.
  • Use dictionary[key] = value to add an entry or update an existing value.
  • Use get(key, default) when a missing key should produce a fallback rather than raise KeyError.
  • Use in to test for keys and values() to test for values.
  • Use keys(), values(), and items() to inspect dictionary contents; items() is especially useful in loops.
  • Dictionary keys must be hashable, and dictionaries preserve insertion order.
  • Trace each operation and verify the exact output, especially when entries are added, updated, or removed.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: