Dictionary in Python is a collection of keys values, used to store data values like a map, which,
unlike other data types which hold only a single value as an element.
A dictionary can be created by placing a sequence of elements within curly {} braces, separated by
‘comma’. Dictionary holds pairs of values, one being the Key and the other corresponding pair
element being its Key:value. Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.
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'}
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
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
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'}
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'}
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.