In Python, a dictionary is a collection of key/value pairs. It is similar to associative arrays in other programming languages.
Creating Dictionaries
A dictionary is created by placing key/value pairs inside curly braces, {}
, separated by commas.
person1 = {'name': 'Linus', 'age': 21}
print(person1) # {'name': 'Linus', 'age': 21}
As we can see, an item of a dictionary is a key/value pair separated by a colon, :
. Here, our dictionary has two items:
Key | Value |
---|---|
'name' | 'Linus' |
'age' | 21 |
Here are more examples of Python dictionaries.
# empty dictionary
my_dict = {}
# dictionary with integer keys
cars = {1: 'BMW', 2: 'Tesla'}
# dictionary with mixed keys
my_dict = {'name': 'Jack', 1: [4, 5]}
Notes
- Keys of a dictionary must be immutable objects (strings, numbers, tuples etc.). We cannot use immutable objects such as lists as keys.
- Keys of a dictionary must be unique for identification.
Access Dictionary Elements
Dictionaries are optimized to get values when the key is known.
Similar to numbered indexes like 0, 1, 2 to get elements from sequences like lists and tuples, keys are used as indexes for dictionaries.
person1 = {'name': 'Linus', 'age': 21}
print(person1['name']) # Linus
print(person1['age']) # 21
Here, person1['name']
gives the value for the 'name'
key. Similarly, person1['age']
gives the value for the 'age'
key.
If we try to access a key that is not in the dictionary, we will get KeyError
.
person1 = {'name': 'Linus', 'age': 21}
print(person1['hobbies']) # KeyError: 'hobbies'
Using get() to Access Dictionary Values
Sometimes, we may just want to know if the key exists or not (instead of getting an error when the key is not found). In such cases, we can use the dictionary's get()
method.
person1 = {'name': 'Linus', 'age': 21}
print(person1.get('name')) # Linus
print(person1.get("hobbies")) # None
Now, we get None
instead of error if the key is not found. Since None
is interpreted as False
, we can use it inside an if statement to make decisions as per our needs.
Add and Change Dictionary Items
Dictionaries are mutable in Python. We can add new items or change the value of existing items by assigning a value.
Change Dictionary Item
If we assign a value to a dictionary key that already exists, the value of the key gets updated.
person1 = {'name': 'Linus', 'age': 21}
# updating the value of the name key
person1['name'] = 'Dennis'
print(person1) # {'name': 'Dennis', 'age': 21}
Add an Item to Dictionary
If we assign a value to a dictionary key that doesn't exist, a new key/value pair (an item) is added to the dictionary.
person1 = {'name': 'Linus', 'age': 21}
# adding an item to the dictionary
person1['hobbies'] = ['coding', 'fishing']
print(person1) # {'name': 'Linus', 'age': 21, 'hobbies': ['coding', 'fishing']}
Remove Items From a Dictionary
We can use the del
statement to remove items from a dictionary.
person1 = {'name': 'Linus', 'age': 21}
# removing the item with the name key
del person1['name']
print(person1) # {'age': 21}
The del
statement can also be used to delete the entire dictionary.
person1 = {'name': 'Linus', 'age': 21}
# removing the entire dictionary
del person1
print(person1) # NameError: name 'person1' is not defined
Using pop() to Remove Items
We can also use the pop()
method to remove items from the dictionary. The method also returns the removed key.
person1 = {'name': 'Linus', 'age': 21}
print(person1.pop('name')) # Linus
print(person1) # {'age': 21}
Python Dictionary Length
We can find the length of a dictionary using the len()
function. For example,
person1 = {'name': 'Linus', 'age': 21}
print(len(person1)) # 2
Python Dictionary Methods
Python has many useful methods that make it really easy to work with dictionaries. Here are the commonly used dictionary methods
Method | Description |
---|---|
clear() |
removes all items from the dictionary |
copy() |
returns the shallow copy of the dictionary |
get() |
returns the value of the specified key |
items() |
returns a view of the dictionary's (key, value) pairs |
pop() |
returns and removes the item with the given key |
popitem() |
returns and removes the last item from the dictionary |
update() |
updates the dictionary with items from another dictionary |
Iterating through a Dictionary
Starting from Python 3.7, the items of a dictionary are ordered. And, we can easily iterate through key/value pairs in a dictionary using the for loop.
person1 = {'name': 'Linus', 'age': 21}
for key in person1:
# getting corresponding value of keys
value = person1[key]
print(f'key: {key}, value: {value}')
Output
key: name, value: Linus key: age, value: 21
Python Dictionary Summary
In Python, a dictionary is
- ordered - items are in order starting from Python 3.7
- mutable - items of can be added/changed
Recommended Reading: Python String