Dictionary
Dictionary – This is known as set/group of elements in
the form with key value pairs.
Dictionary represented by curly bracket { }
Ex.: student={101:’Aman’, 102:’Amar’, 103:’Reeta’}
Creating an Empty Dictionary:
Syntax:
dict_name={ }
DCSIT, KMCLU, Lucknow
Access Dictionary
Ex.1.
>>> student={101:'Aman', 102:'Amar', 103:'Reeta'}
>>> print(student[101])
Aman
>>> print(student[102])
Amar
>>> print(student[103])
Reeta
>>>
>>> print(student)
{101: 'Aman', 102: 'Amar', 103: 'Reeta'}
>>>
DCSIT, KMCLU, Lucknow
Access Dictionary
Ex.3.
>>> fee_stu={'Aman':3000,'Amar':4000, 'Reeta':'Three
Thousand'}
>>> print(fee_stu)
{'Aman': 3000, 'Amar': 4000, 'Reeta': 'Three Thousand'}
>>>
DCSIT, KMCLU, Lucknow
Update data items in Dictionary
Ex.4.1
>>> fee_stu={'Aman':3000,'Amar':4000, 'Reeta':' Three Thousand'}
>>> fee_stu.update({'Rahil':4500})
>>> print(fee_stu)
{'Aman': 3000, 'Amar': 4000, 'Reeta': 'Three Thousand', 'Rahil':
4500}
Add data items in Dictionary
Ex.4.2
>>> student={101:'Aman', 102:'Amar', 103:'Reeta'}
>>> student[104]='Rahi'
>>> print(student)
{101: 'Aman', 102: 'Amar', 103: 'Reeta', 104: 'Rahi'}
>>>
DCSIT, KMCLU, Lucknow
Change value in Dictionary
Ex.5.
>>> student={101:'Aman', 102:'Amar', 103:'Reeta'}
>>> student[102]='Amar Kumar'
>>> print(student)
{101: 'Aman', 102: 'Amar Kumar', 103: 'Reeta'}
>>>
DCSIT, KMCLU, Lucknow