In Python, a dictionary is a collection that allows us to store data in key-value pairs.
Learn Python with Challenges
Solve challenges and become a Python expert.
Create a Dictionary
We create dictionaries by placing key:value pairs inside curly brackets {}
, separated by commas. For example,
# creating a dictionary
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
# printing the dictionary
print(country_capitals)
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England': 'London'}
The country_capitals
dictionary has three elements (key-value pairs).
Note: Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use mutable (changeable) objects such as lists as keys.
# Valid dictionary
my_dict = {
1: "Hello",
(1, 2): "Hello Hi",
3: [1, 2, 3]
}
print(my_dict)
# Invalid dictionary
# Error: using a list as a key is not allowed
my_dict = {
1: "Hello",
[1, 2]: "Hello Hi",
}
print(my_dict)
Tip: We can also use Python's dict() function to create dictionaries.
Python Dictionary Length
We can get the size of a dictionary by using the len() function.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
# get dictionary's length
print(len(country_capitals)) # 3
Access Dictionary Items
We can access the value of a dictionary item by placing the key inside square brackets.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
print(country_capitals["United States"]) # Washington D.C.
print(country_capitals["England"]) # London
Note: We can also use the get() method to access dictionary items.
Change Dictionary Items
Python dictionaries are mutable (changeable). We can change the value of a dictionary element by referring to its key. For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples",
"England": "London"
}
# change the value of "Italy" key to "Rome"
country_capitals["Italy"] = "Rome"
print(country_capitals)
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England': 'London'}
Add Items to a Dictionary
We can add an item to the dictionary by assigning a value to a new key (that does not exist in the dictionary). For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
# add an item with "Germany" as key and "Berlin" as its value
country_capitals["Germany"] = "Berlin"
print(country_capitals)
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'Germany': 'Berlin'}
Note: We can also use the update method() to add or change dictionary items.
Remove Dictionary Items
We use the del
statement to remove an element from the dictionary. For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
# delete item having "United States" key
del country_capitals["United States"]
print(country_capitals)
Output
{'Italy': 'Naples'}
Note: We can also use the pop method() to remove an item from the dictionary.
If we need to remove all items from the dictionary at once, we can use the clear()
method.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
country_capitals.clear()
print(country_capitals) # {}
Python Dictionary Methods
Here are some of the commonly used dictionary methods.
Function | Description |
---|---|
pop() | Remove the item with the specified key. |
update() | Add or change dictionary items. |
clear() | Remove all the items from the dictionary. |
keys() | Returns all the dictionary's keys. |
values() | Returns all the dictionary's values. |
get() | Returns the value of the specified key. |
popitem() | Returns the last inserted key and value as a tuple. |
copy() | Returns a copy of the dictionary. |
Dictionary Membership Test
We can check whether a key exists in a dictionary using the in
operator.
my_list = {1: "Hello", "Hi": 25, "Howdy": 100}
print(1 in my_list) # True
# the not in operator checks whether key doesn't exist
print("Howdy" not in my_list) # False
print("Hello" in my_list) # False
Note: The in
operator checks whether a key exists; it doesn't check whether a value exists or not.
Iterating Through a Dictionary
A dictionary is an ordered collection of items (starting from Python 3.7). Meaning a dictionary maintains the order of its items.
We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
# print dictionary keys one by one
for country in country_capitals:
print(country)
print("----------")
# print dictionary values one by one
for country in country_capitals:
capital = country_capitals[country]
print(capital)