A Python dictionary stores data as key-value pairs. In this tutorial, you will learn how to create dictionaries, access and update values, add or remove items, iterate through entries, use common dictionary methods, and avoid common errors.
Python Dictionary
A Python dictionary is a mutable mapping. Each item contains a unique key associated with a value.
- Keys are unique: assigning a value to an existing key replaces its previous value.
- Values may repeat: different keys can store the same value.
- Dictionaries are mutable: items can be added, updated, and removed.
- Insertion order is preserved: in modern Python, iteration follows the order in which items were added.
- Keys must be hashable: strings, numbers, and tuples containing hashable objects can be keys; lists and dictionaries cannot.
A dictionary is written with curly braces. A colon separates each key from its value, and commas separate the items.
Create a Python Dictionary
To create a Python dictionary, assign comma-separated key-value pairs enclosed in curly braces to a variable.
In the following example, we create a dictionary with some initial key-value pairs.
#initialize tuple
aDict = {
'tallest building':'Burj Khalifa',
'longest river':'The Nile',
'biggest ocean':'The Pacific Ocean'
}
In the above example, tallest building, longest river, and biggest ocean are keys. Burj Khalifa, The Nile, and The Pacific Ocean are their corresponding values.
Create an Empty Dictionary
You can create an empty dictionary with either curly braces or the dict() constructor.
empty_dict_1 = {}
empty_dict_2 = dict()
print(type(empty_dict_1))
print(type(empty_dict_2))
<class 'dict'>
<class 'dict'>
Create a Dictionary with dict()
The dict() constructor can create a dictionary from keyword arguments or from an iterable of key-value pairs.
student = dict(name="Anita", age=20, course="Python")
scores = dict([("math", 92), ("science", 88)])
print(student)
print(scores)
Access Dictionary Values by Key
Use a key inside square brackets to access its value. The key must exist; otherwise, Python raises a KeyError.
Python Program
#initialize tuple
aDict = {
'tallest building':'Burj Khalifa',
'longest river':'The Nile',
'biggest ocean':'The Pacific Ocean'
}
print(aDict['longest river'])
Output
The Nile
Use get() to Avoid KeyError
The get() method returns None when a key is missing, or a default value that you provide.
student = {"name": "Anita", "score": 92}
print(student.get("score"))
print(student.get("grade"))
print(student.get("grade", "Not assigned"))
92
None
Not assigned
Update Values in a Python Dictionary
Assign a new value to an existing key to update that item. You can also use update() to change several items at once.
student = {"name": "Anita", "score": 82}
student["score"] = 92
student.update({"course": "Python", "active": True})
print(student)
{'name': 'Anita', 'score': 92, 'course': 'Python', 'active': True}
Iterate Through Dictionary Keys and Values
To iterate through all key-value pairs of a Python dictionary, you can use a Python For Loop as shown below.
Python Program
#initialize tuple
aDict = {
'tallest building':'Burj Khalifa',
'longest river':'The Nile',
'biggest ocean':'The Pacific Ocean'
}
for key in aDict:
print(key,':',aDict[key])
Output
tallest building : Burj Khalifa
longest river : The Nile
biggest ocean : The Pacific Ocean
For clearer code, use items() when both the key and value are required. Use keys() for keys and values() for values.
student = {"name": "Anita", "score": 92, "course": "Python"}
for key, value in student.items():
print(key, ":", value)
Add a New Key-Value Pair to a Dictionary
To add a new key-value pair, assign a value using a key that is not already present in the dictionary.
Python Program
#initialize tuple
aDict = {
'tallest building':'Burj Khalifa',
'longest river':'The Nile',
'biggest ocean':'The Pacific Ocean'
}
aDict['biggest forest'] = 'The Amazon'
for key in aDict:
print(key, ':', aDict[key])
Output
tallest building : Burj Khalifa
longest river : The Nile
biggest ocean : The Pacific Ocean
biggest forest : The Amazon
Remove Items from a Python Dictionary
Python provides several ways to remove dictionary items:
pop(key)removes a specified key and returns its value.popitem()removes and returns the last inserted key-value pair.del dictionary[key]removes a specified item.clear()removes all items but keeps the dictionary object.
student = {"name": "Anita", "score": 92, "course": "Python"}
removed_score = student.pop("score")
del student["course"]
print(removed_score)
print(student)
92
{'name': 'Anita'}
Check Whether a Dictionary Contains a Key
Use the in or not in operator to test for keys. Membership checks apply to keys, not values.
student = {"name": "Anita", "score": 92}
print("score" in student)
print("grade" not in student)
True
True
Dictionary Length, Keys, Values, and Items
The len() function returns the number of key-value pairs. The keys(), values(), and items() methods return dynamic view objects.
student = {"name": "Anita", "score": 92, "course": "Python"}
print(len(student))
print(list(student.keys()))
print(list(student.values()))
print(list(student.items()))
Nested Python Dictionaries
A dictionary value can itself be another dictionary. Access nested values by applying one key after another.
students = {
"student_1": {"name": "Anita", "score": 92},
"student_2": {"name": "Rahul", "score": 88}
}
print(students["student_1"]["score"])
92
Python Dictionary Comprehension
A dictionary comprehension creates a dictionary from an iterable in a compact form.
{key_expression: value_expression for item in iterable if condition}
squares = {number: number ** 2 for number in range(1, 6)}
print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Copy a Dictionary Without Sharing the Same Object
Using simple assignment does not create a separate dictionary. Both variables refer to the same object. Use copy() or dict() for a shallow copy.
original = {"name": "Anita", "score": 92}
copied = original.copy()
copied["score"] = 95
print(original)
print(copied)
{'name': 'Anita', 'score': 92}
{'name': 'Anita', 'score': 95}
Common Python Dictionary Errors
- KeyError: accessing a missing key with square brackets. Use
get()when a default is appropriate. - Unhashable key: using a list, set, or dictionary as a key.
- Changing size during iteration: adding or deleting items while directly looping over the dictionary can raise a runtime error. Iterate over
list(dictionary)when removal is required. - Confusing assignment with copying:
copy_b = copy_acreates another reference to the same dictionary.
Python Dictionary Operations
Refer to the following tutorials for more focused dictionary operations.
- Get Keys of Python Dictionary as a List Python Tutorial to get all the keys in the given dictionary as a list.
- Get Values of Python Dictionary as a List Python Tutorial to get all the values in the given dictionary as a list.
- Get Length of Python Dictionary Python Tutorial to get the length of given dictionary.
Python Dictionary FAQs
Are Python dictionaries ordered?
Yes. Modern Python dictionaries preserve insertion order, so iteration returns items in the order in which they were added. A dictionary is still a mapping, so items are accessed by key rather than by numeric position.
Can a Python dictionary have duplicate keys?
No. Each key is unique. If the same key appears more than once during creation, or if you assign that key again later, the latest value replaces the earlier one.
What is the difference between dictionary[key] and dictionary.get(key)?
dictionary[key] raises KeyError when the key is missing. dictionary.get(key) returns None, or a specified default value, instead.
Can a list be used as a dictionary key?
No. Dictionary keys must be hashable. Lists are mutable and therefore unhashable. A tuple can be a key when all of its elements are hashable.
Summary of Python Dictionary Usage
In this Python Tutorial, you learned how to create a dictionary, access values by key, use get(), add and update items, remove entries, iterate through keys and values, work with nested dictionaries, create dictionary comprehensions, and copy dictionaries safely.
TutorialKart.com