A Python dictionary consists of a collection of key-value pairs with unique keys. The advantage of using a dictionary is quick access to an element by a key without having to search through a full dataset, which means you can achieve both performance gain and write more readable code.
Dictionary Syntax:
#One-dimensional Dictionary
dictionary_object = { key1: value1, key2: value2, key3: value3 ...}
#Two-dimensional Dictionary
dictionary_object = {
key1: {key11: value11, key12: value12, key13: value13 ...},
key2: {key21: value21, key22: value22, key23: value23 ...},
key3: {key31: value31, key32: value32, key33: value33 ...} ...
}
You need to know about Python’s Dictionary:
- Python’s Dictionary consists of a collection of key-value pairs separated by a comma, and inside curly braces. The keys must be hashable, you also often read those keys must be immutable, but that is just because immutable types (such as number, string, or tuple) are also hashable. The list type can’t be used as the keys because the list is mutable. And the value is a mutable type so you can use all of the data types such as number, string, tuple, or even the list data type.
- The keys must be unique and cannot appear more than once in a collection. If the keys appear more than once, only the last will be retained.
- The keys are case-sensitive.
- The dict is the class of all dictionaries, and a dictionary can also be created using the dict() function.
Let’s see one by one how to create, access, update and delete the dictionary:
Creating Dictionary
Python offers various ways to create a dictionary and, in this post, we have 5 different approaches to do it (and of course, there is another way to do this). So, let’s see what can look like:
Basic Creation of Dictionary
Example #1:
# Basic Creation
empty_dict = {} #Empty Dictionary
int_str_dict = {0: 'Zero', 1: 'One', 2: 'Two'} # int key & string value
float_str_dict = {1.5: 'One and Half', 2.5: 'Two and Half'} # float key & string value
tuple_str_dict = {(1, 2): 'point-a', (5, 5): 'point-b'} #tuple key & string value
str_int_dict = {'One': 1, 'Two': 2, 'Three': 3}
print('empty_dict: {}'.format(empty_dict))
print('int_str_dict: {}'.format(int_str_dict))
print('float_str_dict: {}'.format(float_str_dict))
print('tuple_str_dict: {}'.format(tuple_str_dict))
print('str_int_dict: {}'.format(str_int_dict))
The Output:
empty_dict: {}
int_str_dict: {0: 'Zero', 1: 'One', 2: 'Two'}
float_str_dict: {1.5: 'One and Half', 2.5: 'Two and Half'}
tuple_str_dict: {(1, 2): 'point-a', (5, 5): 'point-b'}
str_int_dict: {'One': 1, 'Two': 2, 'Three': 3}
From the example above, maybe you are wondering in what situations you can use tuples as a dictionary key, classic example is to save some points in the coordinate system, or to save some parameter set in the context of machine learning to find the best combination, etc.
Create Dictionary with dict() function
Example #2:
# Create Dictionary with dict() function
student = dict(name='Paul', email='paul@gmail.com', age=15)
print('student: {}'.format(student))
print('Data Type: {}'.format(type(student)))
The Output:
student: {'name': 'Paul', 'email': 'paul@gmail.com', 'age': 15}
Data Type: <class 'dict'>
Create Dictionary with zip() function
Example #3:
# Create Dictionary with zip() function
paul_key = ('name', 'email', 'age')
paul_value = ('Paul', 'Paul@gmail.com', 15)
student_1 = dict(zip(paul_key, paul_value))
print('student: {}'.format(student_1))
print('Data Type: {}'.format(type(student_1)))
The Output:
student: {'name': 'Paul', 'email': 'Paul@gmail.com', 'age': 15}
Data Type: <class 'dict'>
Create Dictionary with dictionary Comprehensions
Example #4:
# Create Dictionary with dictionary Comprehensions
power_of_two = {base: 2 ** base for base in range(10)}
print('power_of_two: {}'.format(power_of_two))
print('Data Type: {}'.format(type(power_of_two)))
The Output:
power_of_two: {0: 1, 1: 2, 2: 4, 3: 8, 4: 16, 5: 32, 6: 64, 7: 128, 8: 256, 9: 512}
Data Type: <class 'dict'>
Create Dictionary by combining multiple dictionaries
Example #5:
# Create Dictionary by combining multiple dictionaries
animal_1 = {'pig': 10, 'cow': 12, 'dog': 2}
animal_2 = {'cat': 5, 'bird': 6}
animals = {**animal_1, **animal_2}
print('animals: {}'.format(animals))
print('Data Type: {}'.format(type(animals)))
The Output:
animals: {'pig': 10, 'cow': 12, 'dog': 2, 'cat': 5, 'bird': 6}
Data Type: <class 'dict'>
Create a two-dimensional Dictionary
Example #6:
# Create two-dimensional Dictionary
students = {
0: {'name': 'Paul', 'email': 'paul@gmail.com', 'age': 15},
1: {'name': 'Jack', 'email': 'jack@gmail.com', 'age': 13},
2: {'name': 'Biden', 'email': 'biden@gmail.com', 'age': 12}
}
print('students: {}'.format(students))
print('Data Type: {}'.format(type(students)))
The Output:
students: {0: {'name': 'Paul', 'email': 'paul@gmail.com', 'age': 15}, 1: {'name': 'Jack', 'email': 'jack@gmail.com', 'age': 13}, 2: {'name': 'Biden', 'email': 'biden@gmail.com', 'age': 12}}
Data Type: <class 'dict'>
Reading from Dictionary
In a dictionary you can access a value by a key in the square brackets or by a get() function, the difference with the get() function will return None if the key doesn’t exist, and with square brackets will return an error.
Let’s see the below example:
Read a Dictionary with square brackets
Example #7:
# Reading a One-dimensional Dictionary with square brackets
student = dict(name='Paul', email='paul@gmail.com', age=15)
print('Your name is {}, and your age is {}'.format(student['name'], student['age']))
The Output:
Your name is Paul, and your age is 15
Example #8:
# Reading a Two-dimensional Dictionary with square brackets
students = {
1: {'name': 'Paul', 'email': 'paul@gmail.com', 'age': 15},
2: {'name': 'Jack', 'email': 'jack@gmail.com', 'age': 13},
3: {'name': 'Biden', 'email': 'biden@gmail.com', 'age': 12}
}
print('Student No. 2: {}'.format(students[2]))
print('Name: {}'.format(students[2]['name']))
print('Age: {}'.format(students[2]['age']))
The Output:
Student No. 2: {'name': 'Jack', 'email': 'jack@gmail.com', 'age': 13}
Name: Jack
Age: 13
Read a Dictionary with get() function
Example #9:
# Reading a One-dimensional Dictionary with get() function
student = dict(name='Paul', email='paul@gmail.com', age=15)
print('Your name is {}, and your age is {}'.format(student.get('name'), student.get('age')))
The Output:
Your name is Paul, and your age is 15
Example #10:
# Reading a Two-dimensional Dictionary with square brackets
students = {
1: {'name': 'Paul', 'email': 'paul@gmail.com', 'age': 15},
2: {'name': 'Jack', 'email': 'jack@gmail.com', 'age': 13},
3: {'name': 'Biden', 'email': 'biden@gmail.com', 'age': 12}
}
print('Student No. 2: {}'.format(students.get(2)))
print('Name: {}'.format(students.get(2).get('name')))
print('Age: {}'.format(students.get(2).get('age')))
The Output:
Student No. 2: {'name': 'Jack', 'email': 'jack@gmail.com', 'age': 13}
Name: Jack
Age: 13
Now let’s see the example below to compare reading a dictionary with square brackets vs get() function:
Read a Dictionary with square brackets vs get() function if no exists key
Example #11:
# Reading a Dictionary by square brackets
# If the key doensn't exists
fruits = {0: 'Mango', 1: 'Papaya', 2: 'Pineapple'}
print(fruits[3])
The Output:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-97-bcbf878c13e9> in <module>
3 fruits = {0: 'Mango', 1: 'Papaya', 2: 'Pineapple'}
4
----> 5 print(fruits[3])
KeyError: 3
When you use square brackets to access a dictionary with no existing key, a KeyError exception is raised.
Example #12:
# Reading a Dictionary by get() function
# If the key doensn't exists
fruits = {0: 'Mango', 1: 'Papaya', 2: 'Pineapple'}
print(fruits.get(3))
The Output:
None
When you use get() function to access a dictionary with no existing key, it will return None.
Read a Dictionary with for-loop statement and items() function
Example #13:
# Read a Dictionary with for-loop statement and items() function
students = {
1: {'name': 'Paul', 'email': 'paul@gmail.com', 'age': 15},
2: {'name': 'Jack', 'email': 'jack@gmail.com', 'age': 13},
3: {'name': 'Biden', 'email': 'biden@gmail.com', 'age': 12}
}
for no, student in students.items():
[print('{}. {}'.format(no, value)) for key, value in student.items() if key=='name']
The Output:
1. Paul
2. Jack
3. Biden
Retrieve Dictionary Keys and Values
The keys() and values() function will retrieve the keys and values of a dictionary and return dict_keys and dict_values classes respectively.
Example #14:
# Retrieve Dictionary Keys and Values
capital = {'India': 'New Delhi', 'Dominica': 'Roseau', 'Fiji': 'Suva', 'Finland': 'Helsinki'}
print(capital.keys())
print(capital.values())
print(type(capital.keys()))
print(type(capital.values()))
The Output:
dict_keys(['India', 'Dominica', 'Fiji', 'Finland'])
dict_values(['New Delhi', 'Roseau', 'Suva', 'Helsinki'])
<class 'dict_keys'>
<class 'dict_values'>
From the example above you can see keys() and values() function will return dict_keys and dict_values classes respectively. And you can convert these class with list(), tuple(), or set() function.
Example #15:
# Convert dist_keys or dist_values to list, tuple or set
capital = {'India': 'New Delhi', 'Dominica': 'Roseau', 'Fiji': 'Suva', 'Finland': 'Helsinki'}
print(capital.keys())
print(list(capital.keys()))
print(tuple(capital.keys()))
print(set(capital.keys()))
The Output:
dict_keys(['India', 'Dominica', 'Fiji', 'Finland'])
['India', 'Dominica', 'Fiji', 'Finland']
('India', 'Dominica', 'Fiji', 'Finland')
{'Fiji', 'Dominica', 'India', 'Finland'}
Check if a given key already exists in a dictionary
You can check whether a particular key exists in a dictionary collection or not by using the in or not in keywords.
Example #16:
# Check if a given key already exists in a dictionary
capital = {'India': 'New Delhi', 'Dominica': 'Roseau', 'Fiji': 'Suva', 'Finland': 'Helsinki'}
print(True if 'India' in capital.keys() else False)
print(True if 'Mexico' in capital.keys() else False)
print(True if 'India' not in capital.keys() else False)
print(True if 'Mexico' not in capital.keys() else False)
The Output:
True
False
False
True
Updating Dictionary
You need to know when updating a dictionary:
- If the key exists then the new value will update to the dictionary, but
- If the key doesn’t exist then it means a new element will be added to the dictionary
Below example #17 shows you how to update a dictionary using the assignment and update() function, and also how to add an element to the dictionary.
Example #17:
# Update and Add an element to existing dictionary
quantity = {'Mango': 200, 'Banana': 400, 'Apple': 50, 'Pineapple': 30}
print('Before: {}'.format(quantity))
# Update Mango quantity from 200 to 300
quantity['Mango'] = 300
print('Update with Assignment: {}'.format(quantity))
# Update Mango quantity from 300 to 100
quantity.update({'Mango': 100})
print('Update with update(): {}'.format(quantity))
# Add an element to existing dictionary
quantity['Grapes'] = 45
print('Add: {}'.format(quantity))
The Output:
Before: {'Mango': 200, 'Banana': 400, 'Apple': 50, 'Pineapple': 30}
Update with Assignment: {'Mango': 300, 'Banana': 400, 'Apple': 50, 'Pineapple': 30}
Update with update(): {'Mango': 100, 'Banana': 400, 'Apple': 50, 'Pineapple': 30}
Add: {'Mango': 100, 'Banana': 400, 'Apple': 50, 'Pineapple': 30, 'Grapes': 45}
The below example shows you how to update an element in a two-dimensional dictionary.
Example #18:
# Update an element in two-dimensional dictionary
students = {
1: {'name': 'Paul', 'email': 'paul@gmail.com', 'age': 15},
2: {'name': 'Jack', 'email': 'jack@gmail.com', 'age': 13},
3: {'name': 'Biden', 'email': 'biden@gmail.com', 'age': 12}
}
print('Before: {}'.format(students[3]))
students[3]['name'] = 'Putin'
students[3]['email'] = 'putin@gmail.com'
print('After: {}'.format(students[3]))
The Output:
Before: {'name': 'Biden', 'email': 'biden@gmail.com', 'age': 12}
After: {'name': 'Putin', 'email': 'putin@gmail.com', 'age': 12}
Deleting Dictionary
To remove an element from a dictionary you can use del, pop(), and popitem() function. And you can also delete a dictionary with del statement.
The below examples show how to delete an element from a dictionary with del, pop(), and popitem() function.
Example #19:
# Deleting Dictionary’s Element
quantity = {'Mango': 200, 'Banana': 400, 'Apple': 50, 'Pineapple': 30, 'Grapes': 45}
print('Original: {}'.format(quantity))
# Delete an element with popitem() function
quantity.popitem()
print('popitem(): {}'.format(quantity))
# Delete an element with pop() function
key = 'Pineapple'
quantity.pop(key)
print('pop(\'{}\'): {}'.format(key, quantity))
# Delete an element with del statement
key = 'Banana'
del quantity[key]
print('del quantity[\'{}\']: {}'.format(key, quantity))
The Output:
Original: {'Mango': 200, 'Banana': 400, 'Apple': 50, 'Pineapple': 30, 'Grapes': 45}
popitem(): {'Mango': 200, 'Banana': 400, 'Apple': 50, 'Pineapple': 30}
pop('Pineapple'): {'Mango': 200, 'Banana': 400, 'Apple': 50}
del quantity['Banana']: {'Mango': 200, 'Apple': 50}
The below example shows how to delete a dictionary with del statement.
Example #20:
# Deleting Dictionary
quantity = {'Mango': 200, 'Banana': 400, 'Apple': 50, 'Pineapple': 30, 'Grapes': 45}
del quantity
print(quantity)
The Output:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-139-9ef334a4bd11> in <module>
3 del quantity
4
----> 5 print(quantity)
NameError: name 'quantity' is not defined
The NameError indicates that the dictionary object has been removed from memory.
Conclusion
In this post, we talk about how to work with Python’s Dictionary (how to access, update, modify, and delete). And I hope you can use this post can help you on your next projects.
Thank you for following this post and see you in the next post.