A dictionary in python is an unordered collection of elements and each element is a unique key : value
pair. The dictionary is denoted by {}
. Dictionaries are used when you don’t want to access and element using it’s index value and want to use something else.
How to create a Python Dictionary
Creating a python dictionary is easy as putting your items in a box. You just have to place the elements inside curly brackets {}
. Each element should have a key and it’s value and the key should always be unique.
Let’s understand this using a few examples.
dict_1 = {1:'techie', 2:'hours'}
dict_2 = {'color':'black', 'shape':'circle', 'fruit':'banana'}
We created two dictionaries in the above example. Let’s now try to access the elements. We’ll use square brackets []
to access and element and we’ll enter the key value inside the brackets.
dict_1[1]
dict_2['shape']
dict_2['color']
Output :
'techie'
'circle'
'black'
What if we try to access an element that does not exist in the dictionary?
dict_1[4]
# Output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 4
It will give you a key error as the key is not present in the dictionary. If you don’t want dictionary to throw Key Error, you can use a function called .get()
. It will not show you any output but will also not give any error.
dict_1.get(4)
# Output
>>
You can also create a dictionary by combining two different lists with keys and values in each lists respectively. We use zip()
function to achieve this.
keys = [1, 2, 3, 4]
values = ['Monday', 'Tuesday', 'Wednesday', 'Thursday']
new_dict = dict(zip(keys, values))
print(new_dict)
Output :
{1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday'}
Adding an element to a dictionary
There isn’t any specific way to add an element to a dictionary but let’s check the below two easy ways to do so.
old_dict = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday'}
old_dict[5] = 'Friday'
print(old_dict)
old_dict.update({6:'Saturday'})
print(old_dict)
Output :
{1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday'}
{1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday'}
Deleting an element from the Dictionary
We can use del
keyword or pop()
function to remove an element from a dictionary. They both are different in their own ways. We also have clear()
method to clear the complete dictionary.
old_dict = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday'}
old_dict.pop(2)
print(old_dict)
del old_dict[6]
print(old_dict)
Output :
{1: 'Monday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday'}
{1: 'Monday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday'}
Nested Python Dictionary
Python dictionary can also contain another dictionary and this is know as Python Nested Dictionary.
dict_nest = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 'new_dict': {'color': 'black', 'fruit': 'apple'}}
print(dict_nest['new_dict']['fruit'])
Output :
apple
More Python Dictionary methods
clear() | Removes all elements from the dictionary | |
copy() | Returns a copy of the dictionary | |
fromkeys() | Returns a new dictionary with given keys and values | |
get() | Returns value of the given key | |
item() | Returns a list containing tuples of each Key/Value pair | |
keys() | Returns a list of dictionary’s keys | |
pop() | Removes the element with the given key | |
popitem() | Removes the last added Key/value pair | |
setdefault() | Returns value of the given key. If key is missing, inserts key with given value. | |
update() | Updates the dictionary with the given Key/Value pair | |
values() | Returns a list of dictionary’s values |