Python - Datatype - Dictionary Tutorial
Dictionary is a set of unordered( not sequential ) key-value pairs of items. It is a data type, which is used to store a specific value with its key. The item in the dictionary are separated with a comma “,” and curly brackets “{}”.
Dictionary value can be accessed using its corresponding key as an index in a square bracket[]. It will raise the error - KeyError if the key is not found in the dictionary. Using the get function will return None if the key is not found in the dictionary
Value and key can be of any data type, but the key must be unique and immutable.
Dictionary can also be created using the built-in function dict(), user-defined, eval, and zip.
For example-
#Dictionary created with mixed key - user defined
a = {1:"Hello",'abc':2,3.6:4.02,4:["fresherbell",23,45],5:True}
print(type(a))
print (a)
#value can be accessed, by putting the key in square bracket
print (a[4])
print (a[3.6])
#Dictionary using built-in function dict() with integer key
b = dict({1:'Hello', 2:'fresherbell'})
print(type(b))
print (b[1])
#- It will user inner sequence of list as key-value pair
c = [[1,2] , ['name', 'Saurabh'] , [10, 'Sam']]
print(dict(c))
#It will return None if the key is not found in the dictionary
print (b.get(3))
#It will raise an error - KeyError if key is not found in the dictionary
print (b[3])
Output-
<class 'dict'>
{1: 'Hello', 'abc': 2, 3.6: 4.02, 4: ['fresherbell', 23, 45], 5: True}
['fresherbell', 23, 45]
4.02
<class 'dict'>
Hello
{1: 2, 'name': 'Saurabh', 10: 'Sam'}
None
Traceback (most recent call last):
File "jdoodle.py", line 23, in <module>
print (b[3])
KeyError: 3
Creation of dictionary using eval function i.e user input -
# Dictionary created with eval - user input
a = eval(input('data'))
print (a, type(a))
Input-
{1:"Hello",'abc':2,3.6:4.02,4:["fresherbell",23,45],5:True}
Output-
data{1: 'Hello', 'abc': 2, 3.6: 4.02, 4: ['fresherbell', 23, 45], 5: True} <class 'dict'>
Creation of dictionary using the zip function-
# Dictionary created using zip
a = [1,2,3,4,5]
b = [100,200,300,400,500]
print(dict(zip(a,b)))
Output-
{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
Updating and Adding Dictionary Element
Dictionary values are mutable. We can update values using the corresponding key. We can also add a new key: value pair in a dictionary using the assignment operator.
If the key is already present in the key, the corresponding value will get updated. Otherwise, it will add a new key:value pair in the dictionary
Example-
# Dictionary with mixed key
a = {1:"Hello",'abc':2,4:["fresherbell",23,45]}
# Updating Dictionary element
a[4] = 'Python'
print (a)
# Adding Dictionary element
a[2] = 3.14
print (a)
Output-
{1: 'Hello', 'abc': 2, 4: 'Python'}
{1: 'Hello', 'abc': 2, 4: 'Python', 2: 3.14}
Removing Dictionary Element
We can remove a particular element from the dictionary using the pop() method. the pop() method will take the key to remove an item from the dictionary and return the corresponding value.
While popitem() will remove the last item from the dictionary and also return the removed item in a form of (key: value) pair from the dictionary.
clear() will clear all the items from the dictionary and will return none.
a del keyword can be used to delete a whole dictionary or an individual item.
Example-
# Dictionary with mixed key
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
# Removing a Dictionary element using pop()
print (a.pop('abc'))
print (a)
# Removing a Dictionary last element using popitem()
print (a.popitem())
print (a)
# Removing a Dictionary all elements using clear()
print (a.clear())
print (a)
#Again defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
del a['abc']
print (a)
# Deleting the whole dictionary
del a
print (a)
Output-
2
{1: 'Hello', 4: ['fresherbell', 23, 45], 5: True}
(5, True)
{1: 'Hello', 4: ['fresherbell', 23, 45]}
None
{}
{1: 'Hello', 4: ['fresherbell', 23, 45], 5: True}
Traceback (most recent call last):
File "jdoodle.py", line 28, in <module>
print (a)
NameError: name 'a' is not defined
Dictionary Built-in function
- clear() – It will remove all items from the dictionary.
Example-
# Removing a Dictionary all elements using clear()
print (a.clear())
print (a)
Output-
None
{}
- copy() – It will copy all items from one dictionary to another dictionary.
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
#copying dictionary a to dictionary b
b = a.copy()
print (b)
Output-
{1: 'Hello', 'abc': 2, 4: ['fresherbell', 23, 45], 5: True}
- fromkeys() – it will create a new dictionary from the given sequence of elements as a key. Value is optional. If the value is not set, by default it will take none.
Example-
#defining key in sequence
key1 = {1,2,3,4}
#making new dictionaries from key
a = dict.fromkeys(key1)
print(a)
#defining value in the sequence
value1 = 'values'
b = dict.fromkeys(key1,value1)
print(b)
Output-
{1: None, 2: None, 3: None, 4: None}
{1: 'values', 2: 'values', 3: 'values', 4: 'values'}
- get() – It will return a value of a specified key.
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
print (a.get('abc'))
Output-
2
- items() – It will return a view object that displays a list of all the keys:value pair from the dictionary.
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
print (a.items())
Output-
dict_items([(1, 'Hello'), ('abc', 2), (4, ['fresherbell', 23, 45]), (5, True)])
- popitem() – It will remove the last item from the dictionary and also return the removed item in a (key: value) pair from the dictionary.
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
print (a.popitem())
print (a)
Output-
(5, True)
{1: 'Hello', 'abc': 2, 4: ['fresherbell', 23, 45]}
- pop() – It will take the key to remove an item from the dictionary and return the corresponding value.
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
print (a.pop('abc'))
print (a)
Output-
2
{1: 'Hello', 4: ['fresherbell', 23, 45], 5: True}
- setDefault() – It will return the value of a key, which is present in the dictionary. Otherwise, it will insert a new key with the default value none, if no value is provided with the key.
Example-
#defining dictionary
a = {1:"Hello"}
#if the key is not in the dictionary
#It will add a new key in the dictionary with default value none if no value is been provided
a.setdefault(2)
print (a)
#if the key is not in the dictionary
#And the value is provided, then it will add the provided value with key
a.setdefault(3, 'Fresherbell')
print (a)
Output-
{1: 'Hello', 2: None}
{1: 'Hello', 2: None, 3: 'Fresherbell'}
- keys() – It will return a view object that displays a list of all the keys from the dictionary.
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
print (a.keys())
Output-
dict_keys([1, 'abc', 4, 5])
- values() – It will return a view object that display a list of all the values from the dictionary.
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
print (a.values())
Output-
dict_values(['Hello', 2, ['fresherbell', 23, 45], True])
- update() – It will update the new value to the key if the key is already present in dictionary. Otherwise, it will add new entry, if key is not present in dictionary.
Example-
a = {1:"Hello",2:'abc'}
#update the value of key 2
n1 = {2:'fresherbell'}
a.update(n1)
print(a)
#it will add new element if key is not present in dictionary
n2 = {3:'.in'}
a.update(n2)
print(a)
Output-
{1: 'Hello', 2: 'fresherbell'}
{1: 'Hello', 2: 'fresherbell', 3: '.in'}
- len() – It will return the length of the dictionary.
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
# To get the length of dictionary
print(len(a))
Output-
4
Using For Loop in the dictionary
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
# using for loop in the dictionary
# We can iterate through each key in a dictionary using for loop.
for i in a:
print(a[i])
Output-
Hello
2
['fresherbell', 23, 45]
True
To check whether the key is in the dictionary or not
We can check whether the key is a dictionary or not using in and not in the keyword. It will return the output in the form of Boolean (True or False)
Example-
#defining dictionary
a = {1:"Hello",'abc':2,4:["fresherbell",23,45],5:True}
# To check whether a key in dictionary or not
print(1 in a)
print(2 in a)
print(2 not in a)
Output-
True
False
True
Dictionary Comprehension
Dictionary Comprehension is a short syntax or one-line code used when you want to create a new dictionary in an elegant and concise way.
Syntax-
newdict = {key: value for (key, value) in iterable}
Advantages are-
- Time Efficient & Space Efficient
- Fewer lines of code
For example-
newdict = { i: i**2 for i in range(6)}
print(newdict)
Output-
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}