Dictionary
The dictionary is an unordered collection of items. An item is a key-value pair.
The key in a dictionary allows retrieving the value optimally.
Creating a dictionary
The dictionary is created by placing key-value pairs inside curly braces where a key-value pair is separated by commas. The key-value pair is separated by a colon.
A key must be immutable type, however value can be immutable or mutable. The key must be unique in a dictionary.
_dict = {1:'a', 2:'b' , 3:'c', 4:'d'}
print(_dict)
_dict = {'a':1,'b':[1,2,3] , 'c':(1,2,3), 'd':4}
print(_dict)
_dict = {"id":123, "emp name":"ramesh", "age": 24}
print(_dict)
#Creating an empty dictionary
_dict= {}
print(_dict)
Output
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
{'a': 1, 'b': [1, 2, 3], 'c': (1, 2, 3), 'd': 4}
{'id': 123, 'emp name': 'ramesh', 'age': 24}
{}
Creating dictionary using dict() function
There are various ways to create the dictionary these are
Create Dictionary Using keyword arguments
point = dict(x1=0,y1=0, x2=1,y2=1)
print(point)
Output
{'x1': 0, 'y1': 0, 'x2': 1, 'y2': 1}
Create a dictionary using an Iterable
# Create dictionary using a list of tuples
point = dict( [('x1',0),('y1',0)])
print(point)
# Create dictionary using a list of tuples and keyword argument
point3d = dict( [('x',0),('y',0)] , z=0)
print(points)
# Create dictionary using a lists for key and values and zip
point3d = dict(zip(['x', 'y', 'z'], [1, 2, 3]))
print(point3d)
Output
{'x1': 0, 'y1': 0}
{'x': 0, 'y': 0, 'z': 0}
{'x': 1, 'y': 2, 'z': 3}
Create a dictionary using Mapping
_dict= dict({'x1': 0, 'y1': 0})
print(_dict)
Output
{'x1': 0, 'y1': 0}
Accessing items from a dictionary
The key is used to retrieve the values from a dictionary. The get() function and [] square are used to retrieve a value.
_dict = {"id":123, "emp name":"ramesh", "age": 24}
print(_dict.get("id"))
print(_dict["age"])
Output
123
24
Note: The difference between using get() and the square bracket is, square brackets raises a KeyError if the key is not found in the dictionary, whereas the get() function returns None if the key is not found.
Add or modify an item to a dictionary
Dictionaries are mutable, it is possible to add a new item or change the value of an existing item using an assignment operator.
Note: If the key is already exists, then the existing value gets updated otherwise, a new (key: value) pair (item) is added to the dictionary.
_dict = {"id":123, "emp name":"ramesh", "age": 24}
# Modify the value of the key age
_dict["age"]= 27
print(_dict)
# Add an item to a dictionary
_dict["Band"]= 'E'
print(_dict)
Output
{'id': 123, 'emp name': 'ramesh', 'age': 27}
{'id': 123, 'emp name': 'ramesh', 'age': 27, 'Band': 'E'}
Removing item(s) from a dictionary
There are various ways to remove item(s) from a dictionary
- A particular item is removed by using the pop() function. The pop(key) function removes an item and returns its value.
- The popitem() function removes and returns an arbitrary (key, value) pair from a dictionary.
- The clear() function removed all the items from the dictionary.
- The del removes the dictionary or an item
vowels = {'a':1, 'e':2,'i': 3, 'o':4, 'u':5, 'A':6}
print("The removed value is ", vowels.pop('A'))
print(vowels)
print("The removed item is ",vowels.popitem())
vowels = {'a':1, 'e':2,'i': 3, 'o':4, 'u':5, 'A':6}
del vowels['a']
print("Dictionary after removing key 'a'' ", vowels)
vowels.clear()
print("Dictionary after clearing all the items ", vowels)
vowels = {'a':1, 'e':2,'i': 3, 'o':4, 'u':5, 'A':6}
del vowels
print(vowels)
Output
The removed value is 6
{'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5}
The removed item is ('u', 5)
Dictionary after removing key 'a'' {'e': 2, 'i': 3, 'o': 4, 'u': 5, 'A': 6}
Dictionary after clearing all the items {}
Traceback (most recent call last):
File "dice.py", line 748, in <module>
print(vowels)
NameError: name 'vowels' is not defined
Iterating through a Dictionary
vowels = {'a':1, 'e':2,'i': 3, 'o':4, 'u':5}
#items function return dictionary contains a list of
# key value pair in tuples
for item in vowels.items():
print(item)
#printing all the key of a dictionary
for key in vowels:
print(key)
#printing all the values
for key in vowels:
print(vowels.get(key))
Output
('a', 1)
('e', 2)
('i', 3)
('o', 4)
('u', 5)
a
e
i
o
u
1
2
3
4
5
How to retrieve all the keys from a dictionary
The keys() function returns an iterable of keys for example
_dict = {1:'a',2:'b', 3:'c'}
#print all the keys in a dictionary
for key in _dict.keys():
print(key)
Output
1
2
3
How to retrieve all the values from a dictionary
The values() function returns an iterable of values for example
# print all the values in a dictionary
for value in _dict.values():
print(value)
Output
a
b
c
Membership Test
The ‘in’ and ‘not in’ operators check the existence of a key in a dictionary for example
_dict = {1:'a',2:'b', 3:'c', 4:'d'}
print( 1 in _dict)
print( 5 in _dict)
print( 4 not in _dict)
print( 5 not in _dict)
Output
True
False
False
True
Concatenate dictionaries
The update() function is used to concatenate the dictionary
Note: If the keys are same in both the dictionary the value is overwritten for that key
_dict1 = {1:2, 2:3}
_dict2= {3:4, 4:5}
_dict1.update(_dict2)
print("Dictionay after update " ,_dict1)
_dict1 = {1:2, 2:3}
_dict2 = {1:10, 4:5}
_dict1.update(_dict2)
print("Dictionay after update value is overwritten",_dict1)
Output
Dictionay after update {1: 2, 2: 3, 3: 4, 4: 5}
Dictionay after update value is overwritten {1: 10, 2: 3, 4: 5}