Table of Contents
Dictionary Datatype in Python
Python supports many simple and compound datatypes.
Few data types like list, dictionary are mutable and others like string datatype, tuple are immutable.
Mutable datatypes means changes can be done and are reflected in same variable.
Immutable datatypes means changes can be done but not in same variable.
What is dictionary?
Dictionary is an unordered collection of key-value pairs.
An empty dictionary represents zero character or we can call it as null dictionary indicating False boolean value.
A dict datatype can be defined with use of { key : value, key : value } pairs separated by comma.
Keys should be unique and values can have same data.
Keys defined must be of immutable datatype like string, integers, tuples etc. where as values can be mutable datatype.
But dictionary as a whole is a mutable datatype.
Example
>>> itv1={"name" : "Stark", "class" : "F Y C S", "roll no" : 1}
>>> itv1
{'roll no': 1, 'class': 'F Y C S', 'name': 'Stark'}
>>> type(itv1)
<class 'dict'>
>>> itv1["name"] #key is used to access value
'Stark'
>>> itv1["roll no"] #key is used to access value
1
>>> itv1["class"] #key is used to access value
'F Y C S'
>>> itv1.keys()
dict_keys(['roll no', 'class', 'name'])
>>> itv1.values()
dict_values([1, 'F Y C S', 'Stark'])
>>>
In above example when we print itv1 the output order is not same as input order because dictionary is unorderd datatype.
itv1.keys() prints all the keys present in the dict.
itv1.values() prints all the values present in the dict.
Accessing a dictionary
Like list, tuple, string etc we do not have index value to access dictionary, we can access dictionary with the help of keys given.
A dict can be accessed using square brackets[ ] with key written inside it.
Example
>>> itv= {} #empty dictionary
>>> itv
{}
>>> itv1={1:'welcome',2:'to',3:'itvoyagers'}
>>> itv1[2]
'to'
>>> itv1[4]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
itv1[4]
KeyError: 4
>>> itv1[0]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
itv1[0]
KeyError: 0
>>>
Above example shows how an empty dictionary is defined. Also itv1 has 3 values with keys as 1,2,3 so while accessing the dictionary we use this keys and not the indexes so itv1[0] gives error as 0 is not the key also itv1[4] has 4 which is not available in dictionary.
len function or len()
Python provides a built-in function called as len() to calculate number of items in a dictionary or simply we can say length of a dictionary.
Example:
>>> itv1={"name" : "Stark", "class" : "F Y C S", "roll no" : 1}
>>> len(itv1)
3
>>> itv= {} #empty dictionary
>>> len(itv)
0
Above example calculates the length of dictionary by calculating number of pairs present.
Updating dictionary
You can update dictionary using update method.
A new key : value pair will be added or removed from dictionary to modify existing dictionary.
Example
#accessing values in dictionary
mydict={'Name':'sachin','Marks':50,'Subject':'python'}
print("mydict['Name']",mydict['Name'])
print("mydict['Marks']",mydict['Marks'])
print("mydict['Subject']",mydict['Subject'])
print("mydict before update()",mydict)
#update existing marks
mydict['Marks']=65
print("mydict['Marks']",mydict['Marks'])
print("mydict after update()",mydict)
dict1={'name':'riya','age':25,'rollno':5}
print("dict1 before update()",dict1)
#using update()
dict1.update({'fav_subject':'python'})
print("dict1 after update()",dict1)
OUTPUT

Deleting items from dictionary
The del statement is used to delete items or pairs from dictionary.
It is possible to delete particular item from dictionary as it is of immutable datatype.
Also we can delete entire dict at at a time.
Example

Properties of dictionary
There is no restriction on values of dictionary as we can have any datatype in place of value.
But for keys we have two properties to consider:
- We cannot enter more than one entry per key. It means duplicate key is not allowed, but in case we create a duplicate key then the latest key will be considered.
>>> dict1={'age': 25, 'rollno': 5, 'name': 'riya', 'fav_subject': 'python'}
>>> dict1
{'age': 25, 'rollno': 5, 'name': 'riya', 'fav_subject': 'python'}
>>> dict1={'age': 25, 'rollno': 5, 'name': 'riya', 'fav_subject': 'python','rollno': 6}
>>> dict1
{'age': 25, 'rollno': 6, 'name': 'riya', 'fav_subject': 'python'}
>>>
- As keys are immutable we can have integer,string or tuples as keys and not the mutable datatype.
>>> dict2={['name'] : 'strange','age':45}
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
dict2={['name'] : 'strange','age':45}
TypeError: unhashable type: 'list'
>>>
Other python related post
Other advance python related post
