Hello Everybody, and welcome to Hacoder. Today, we are going to discuss about Dictionary in Python.
If you have no knowledge of Python and still haven’t checked out our previous Python Tutorials, then click here.
So, without wasting time, lets get started!
Dictionary in Python:
Python dictionary is an unordered collection of items. In Dictionary, Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces.
An empty dictionary without any items is written with just two curly braces, like this: {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
Let’s take a look how Dictionary is created and accessed in Python.
1
2
3
4
5
6
7
8
9
|
# Let’s create a dictionary and assign some values to it.
family = {‘Hacoder’: ‘Discover the art of Coding and Hacking’, ‘Webster’: ‘Creates awesome Python Tutorial’, ‘Luka’: ‘Jack of all trades and master of them too’ }
print(family) #Prints all the elements of Dictionary
# Output: {‘Hacoder’: ‘Discover the art of Coding and Hacking’, ‘Luka’: ‘Jack of all trades and master of them too’, ‘Webster’: ‘Creates awesome Python Tutorial’}
print(family[‘Webster’])
# Output: Creates awesome Python Tutorial
|
The output of the above program will be:
{‘Hacoder’: ‘Discover the art of Coding and Hacking’, ‘Luka’: ‘Jack of all trades and master of them too’, ‘Webster’: ‘Creates awesome Python Tutorial’}
Creates awesome Python Tutorial
Updating Dictionary:
We can update an existing dictionary by adding a new entries, modifying an existing entry, or deleting an existing entry.
1
2
3
4
5
6
7
8
9
10
11
12
|
#Ok Lets Update the previous Dictionary
family = {‘Hacoder’: ‘Discover the art of Coding and Hacking’, ‘Webster’: ‘Creates awesome Python Tutorial’, ‘Luka’: ‘Jack of all trades and master of them too’ }
# Updating existing entry
family[‘Webster’] = ‘Python freak’
# Adding new entry
family[‘Ibrahim’] = ‘Hacker’
print(family[‘Ibrahim’])
print(family[‘Webster’])
|
The output of this code is:
Hacker
Python freak
Deleting Dictionary:
We can remove individual dictionary elements or clear the entire contents of a dictionary. We can also delete entire dictionary in a single operation.
1
2
3
4
5
6
7
8
9
|
#Deleting the Dictionary
family = {‘Hacoder’: ‘Discover the art of Coding and Hacking’, ‘Webster’: ‘Creates awesome Python Tutorial’, ‘Luka’: ‘Jack of all trades and master of them too’ }
del family[‘Webster’] # remove entry with key ‘Webster’
family.clear() # Removing all the entries of dictionary
del family # Delete the entire dictionary
|
That was all about Dictionary in Python. Learn more about Dictionaries in Python from the Official Python Documentation.
If you have any questions or suggestion, feel free to tell us in the comments section below.