Last modified: Jan 27, 2026 By Alexander Williams
Python Dictionary Keys: Guide & Examples
Python dictionaries are powerful data structures. They store data as key-value pairs. Understanding keys is fundamental to using dictionaries effectively. This guide covers everything you need to know.
What Are Dictionary Keys?
A dictionary key is a unique identifier for a value. Think of it like a label on a file folder. The key lets you find the specific data you need quickly. Keys are used to access, modify, and manage dictionary items.
Keys must be immutable and hashable. This means their value cannot change after creation. Common key types include strings, numbers, and tuples.
Creating Dictionaries with Keys
You can create a dictionary by enclosing key-value pairs in curly braces {}. Use a colon to separate each key from its value.
# Creating a dictionary with different key types
student = {
"name": "Alex", # String key
101: "Roll Number", # Integer key
(1, 2): "Tuple Key" # Tuple key (immutable)
}
print(student)
{'name': 'Alex', 101: 'Roll Number', (1, 2): 'Tuple Key'}
Notice how we used an integer and a tuple as keys. This is allowed because they are immutable. Lists cannot be keys because they are mutable.
Accessing Values Using Keys
To get a value, place its key inside square brackets [] after the dictionary name. This is fast and direct.
inventory = {"apples": 50, "bananas": 30, "oranges": 25}
# Access value for the key "bananas"
quantity = inventory["bananas"]
print(f"Bananas in stock: {quantity}")
Bananas in stock: 30
If you try to access a key that doesn't exist, Python raises a KeyError. To avoid this, use the get() method. It returns None or a default value if the key is missing.
print(inventory.get("grapes")) # Key doesn't exist
print(inventory.get("grapes", 0)) # Returns default value 0
None
0
Key Immutability and Hashability
This is a critical rule. A dictionary key must be of an immutable data type. This ensures the key's hash value never changes. If it changed, Python couldn't find the associated value.
Valid keys: Strings, integers, floats, booleans, tuples (containing only immutables).
Invalid keys: Lists, sets, dictionaries (all are mutable).
# This will cause a TypeError
invalid_dict = {["list", "key"]: "value"}
Running this code results in: TypeError: unhashable type: 'list'.
Checking for Key Existence
Before accessing a key, you often need to check if it exists. Use the in keyword. It returns True or False.
config = {"theme": "dark", "language": "en"}
if "theme" in config:
print("Theme setting is present.")
if "font_size" not in config:
print("Font size is not configured.")
Theme setting is present.
Font size is not configured.
Getting All Keys with .keys()
The keys() method returns a view object. It displays all keys in the dictionary. This view updates automatically if the dictionary changes. For a complete overview of dictionary tools, see our Python Dictionary Methods Guide & Examples.
colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}
key_view = colors.keys()
print(key_view)
print(list(key_view)) # Convert to a list
dict_keys(['red', 'green', 'blue'])
['red', 'green', 'blue']
Adding and Modifying Keys
Adding a new key is simple. Assign a value to a new key name. To modify an existing key, assign a new value to it. You can also use the update() method to add or modify multiple keys at once. Learn more in our dedicated Python Dict Update Method Guide & Examples.
scores = {"math": 90}
scores["science"] = 85 # Add new key
scores["math"] = 95 # Modify existing key
print(scores)
{'math': 95, 'science': 85}
Removing Keys
To delete a key-value pair, use the del statement. The pop() method removes a key and returns its value. This is useful when you need the value after removal. For a deeper dive, check out Python Dict Pop: Remove and Return Items.
data = {"a": 1, "b": 2, "c": 3, "d": 4}
del data["a"] # Permanently removes key "a"
removed_value = data.pop("b") # Removes "b" and returns 2
print(f"Removed value: {removed_value}")
print(f"Dictionary after deletions: {data}")
Removed value: 2
Dictionary after deletions: {'c': 3, 'd': 4}
Remember, dictionaries do not have a remove() attribute. Trying to use it causes an error.
Key Order in Dictionaries
In Python 3.7+, dictionaries maintain insertion order. This means keys are stored in the order you add them. This was not guaranteed in earlier versions.
ordered_dict = {}
ordered_dict["zebra"] = 1
ordered_dict["ant"] = 2
ordered_dict["cat"] = 3
print(list(ordered_dict.keys()))
['zebra', 'ant', 'cat']
The keys are returned in the exact order they were added.
Iterating Over Keys
Looping through keys is a common task. You can iterate directly over the dictionary or use the keys() method. Both give the same result.
book = {"title": "Python Guide", "author": "Jane Doe", "year": 2023}
# Method 1: Direct iteration (iterates over keys)
for key in book:
print(f"Key: {key}")
# Method 2: Using .keys()
for key in book.keys():
value = book[key]
print(f"{key}: {value}")
Key: title
Key: author
Key: year
title: Python Guide
author: Jane Doe
year: 2023
Common Key Operations Summary
Here is a quick reference table for key operations:
- Access:
dict[key]ordict.get(key) - Check:
key in dict - Get All:
dict.keys() - Add/Modify:
dict[key] = valueordict.update() - Remove:
del dict[key]ordict.pop(key)
Conclusion
Mastering dictionary keys is essential for Python programming. Keys provide fast, direct access to your data. Remember the rules: keys must be immutable and hashable. Use methods like get(), keys(), and pop() to work with keys safely and efficiently. With this knowledge, you can structure your data effectively and write cleaner, more powerful Python code.