VMware ESXi and vSphere Cluster Management
Python Dictionaries: Keys, Values, Access, and Updates
Learn Python dictionaries, including key-value pairs, creation, lookup, updates, deletion, iteration, mutability, and the difference between dictionaries and sets.
A dictionary is a mutable Python mapping that connects unique keys to values. A mapping is a collection organized by associations between keys and values rather than by numeric positions.
Dictionaries are useful for organizing related attributes and for looking up data. For example, a person can have keys such as "name", "height_cm", and "eye_color". Each key identifies the value stored under it.
Lists usually provide position-based access, such as numbers[0] for the first item. Dictionaries provide named, key-based access, such as person["eye_color"]. Use a list when positions are the important part; use a dictionary when meaningful names identify the data.
Dictionary structure: key-value pairs
A dictionary contains one or more key-value pairs. A key-value pair is one association written as key: value.
- Curly braces,
{}, delimit a dictionary literal. - A key identifies an entry.
- A colon,
:, separates a key from its value. - A value is the data associated with the key.
- Commas separate multiple key-value pairs.
person = {
"eye_color": "blue",
"height_cm": 165,
"weight_kg": 53
}
empty_dictionary = {}
| Component | Example | Meaning |
|---|---|---|
| Curly braces | {} | Mark the beginning and end of a dictionary literal. |
| Key | "height_cm" | Identifies the entry. |
| Colon | : | Separates the key from its value. |
| Value | 165 | Data stored under the key. |
| Comma-separated pairs | "a": 1, "b": 2 | Separates multiple entries. |
Creating dictionaries
The simplest way to create a dictionary is with a dictionary literal: write key-value pairs between curly braces.
person = {
"eye_color": "blue",
"height_cm": 165,
"weight_kg": 53
}
Keys in this example are strings, while the values include both a string and integers. Values can have many types:
profile = {
"name": "Amina",
"age": 24,
"is_student": True,
"favorite_colors": ["blue", "green"],
"contact": {"email": "amina@example.com"}
}
Values do not need to be unique. Several keys may refer to equal values. A value may be a string, number, Boolean, list, tuple, another dictionary, or almost any other Python object. A dictionary stored inside another dictionary is called a nested dictionary.
Keys and key requirements
A key is a unique identifier used to find a value. Keys must be unique within one dictionary and must be hashable. An object is hashable when its hash value remains stable during its lifetime, allowing Python to use it as a dictionary key.
Common beginner-friendly hashable keys include strings, integers, and tuples:
data = {
"username": "amina",
42: "the answer",
(2026, "python"): "course topic"
}
Lists and dictionaries cannot be keys because they are mutable and therefore unhashable:
# Invalid: a list cannot be a dictionary key
# lookup = {["red", "green"]: "colors"}
# Invalid: a dictionary cannot be a dictionary key
# lookup = {{"language": "Python"}: "data"}
If the same key appears more than once, the later value replaces the earlier value:
settings = {"theme": "light", "theme": "dark"}
print(settings)
# {'theme': 'dark'}
Accessing dictionary values
Use square brackets with a known key to perform a dictionary lookup. Bracket lookup returns the value, not the key-value pair.
person = {"eye_color": "blue", "height_cm": 165}
color = person["eye_color"]
print(color)
# blue
If the requested key is absent, bracket lookup raises a KeyError:
person = {"eye_color": "blue"}
# print(person["nickname"])
# KeyError: 'nickname'
Use get() when a key may be missing. It returns the value if the key exists, or None by default when it does not. You can provide a different default value.
nickname = person.get("nickname")
print(nickname)
# None
message = person.get("nickname", "No nickname available")
print(message)
# No nickname available
Adding and updating entries
Assignment with a key adds a new entry when the key is not present:
person = {"eye_color": "blue", "height_cm": 165}
person["age"] = 24
The same syntax updates an existing entry when the key is already present:
person["height_cm"] = 170
Therefore, dictionary[key] = value either adds or replaces an entry, depending on whether the key already exists.
Use update() to add or change multiple entries at once:
person.update({
"weight_kg": 53,
"eye_color": "green"
})
Dictionary mutability
Mutable means able to be changed after creation. Dictionaries are mutable: you can add entries, update values, and delete entries without creating a new dictionary.
This is separate from the key requirement. The dictionary itself may change, but each key must be hashable and stable while it is being used as a key. A list cannot be a key because its contents can change; a dictionary cannot be a key for the same reason.
Inspecting dictionary contents
The methods keys(), values(), and items() let you inspect a dictionary:
person = {
"eye_color": "blue",
"height_cm": 165,
"weight_kg": 53
}
print(person.keys())
print(person.values())
print(person.items())
keys()provides the dictionary's keys.values()provides its values.items()provides its key-value pairs.
The in operator checks keys by default. Test for a key before bracket lookup when the key may not exist:
if "weight_kg" in person:
print(person["weight_kg"])
Removing entries
Use del when you know the key and want to remove its entry:
del person["weight_kg"]
Use pop() to remove an entry and return its value:
person = {"name": "Amina", "age": 24}
removed_value = person.pop("age")
print(removed_value)
# 24
If the key is missing, pop() raises a KeyError unless you provide a default:
age = person.pop("age", None)
Iterating through a dictionary
A for loop over a dictionary visits its keys:
person = {"name": "Amina", "age": 24}
for key in person:
print(key)
Use items() when you need both the key and its value. This is useful for processing each association in a structured record:
for attribute, value in person.items():
print(attribute, value)
Nested dictionaries
A nested dictionary is a dictionary stored as a value inside another dictionary. You can perform multiple lookups to reach the nested value:
student = {
"name": "Amina",
"scores": {"math": 92, "science": 88}
}
print(student["scores"]["math"])
# 92
Dictionary operations at a glance
| Task | Syntax | Result or behavior |
|---|---|---|
| Create a dictionary | data = {"key": "value"} | Creates a dictionary with one entry. |
| Access a value | data["key"] | Returns the value or raises KeyError if absent. |
| Safely access an optional value | data.get("key", "default") | Returns the value or the default. |
| Add an entry | data["new_key"] = "new_value" | Adds a new key-value pair. |
| Update an entry | data["key"] = "replacement" | Replaces the value for an existing key. |
| Check for a key | "key" in data | Returns True or False. |
| Delete an entry | del data["key"] | Removes a known key and its value. |
| Iterate through pairs | for key, value in data.items(): | Processes every key-value pair. |
Dictionaries versus sets
A set is an unordered collection of unique standalone values. A dictionary stores key-value pairs. Both can use curly braces when written as literals, but their contents distinguish them:
profile = {"name": "Amina"} # dictionary
colors = {"blue", "green", "red"} # set
empty_dictionary = {} # dictionary
empty_set = set() # set
| Feature | Dictionary | Set |
|---|---|---|
| Stored data | Key-value pairs | Standalone values |
| Literal syntax | {"key": "value"} | {"blue", "green"} |
| Empty collection syntax | {} | set() |
| Access method | Look up values by key | Test membership; there are no keys |
| Uniqueness rule | Keys must be unique | Values must be unique |
Troubleshooting common dictionary mistakes
- A lookup raises
KeyError: The key may be absent, misspelled, or have different capitalization. Checkdata.keys(), useif key in data, or useget()with a suitable default. - A list is used as a key: Lists are mutable and unhashable. Use an immutable key such as a string, integer, or appropriate tuple.
- Two entries become one: Keys must be unique. Assigning the same key again replaces its old value. Use distinct keys for separate entries.
- An empty collection is a dictionary instead of a set: Empty curly braces create an empty dictionary. Use
set()for an empty set. - Code treats dictionary access like list indexing: Dictionaries use keys, not numeric positions, unless numeric keys were explicitly created. Use the relevant key, or use a list when positional access is required.
Summary
- A dictionary is a mutable mapping from unique, hashable keys to values.
- Dictionary literals use curly braces, colons between keys and values, and commas between pairs.
- Use square brackets for required-key lookup and
get()for safe optional lookup. - Assignment with a key adds a new entry or updates an existing one.
- Use
keys(),values(),items(),in,del, andpop()to inspect and modify contents. - Use
items()in a loop when both keys and values are needed. - Unlike dictionaries, sets contain standalone unique values;
{}creates a dictionary, not an empty set.
Continue practicing with Python dictionaries by creating records, looking up optional fields, and iterating through their key-value pairs.