Basics of Dictionary in Python - Jupyter Notebook
Basics of Dictionary in Python - Jupyter Notebook
# Dictionary in python
'''
Dictionary in python is an ordered collection of data values, used to store
data values like a map which unlike other data types that hold only single value
as an element.'''
#empty dictionary
a = {}
print (a)
print (type(a))
b={}
b=set()
print (b)
print (type(b))
{}
<class 'dict'>
set()
<class 'set'>
In [7]: #SET
#c={1,2,3,4} or c=set()
#type(c)
#c={} #dictionary
#type(c)
print (x['age']) #pass key and return value of the key #56
# get ()
print (x.get('age')) # 56
print (x.get(56)) # [12,34,76,8]
56
56
[12, 34, 76, 8]
In [19]: print (x.get('address')) #address key does not exist into x dictionary
#get() method return the NONE if key does exist into x dictionary
print (x['address'])
# it will return the error because by index passing
# we are tyring to access by forcefully to retrive the such key value
None
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-19-9f53ccf4c865> in <module>
1 print (x.get('address')) #address key does not exist into x dictionary
----> 2 print (x['address'])
KeyError: 'address'
print (z)
{1: 56, 2: 68, 3: 434, 4: 500, 5: 98, 6: 1234, 7: 9487, 'address': 'New Delhi'}
In [23]: # If there is no existence of any key and we try to update or assign some value
# then it add automatically without affecting others key of the dictionary
z['age'] = 99
print (z)
{1: 56, 2: 68, 3: 434, 4: 500, 5: 98, 6: 1234, 7: 9487, 'address': 'New Delhi',
'age': 99}
{1: 56, 2: 68, 3: 434, 4: 500, 5: 98, 6: 1234, 7: 9487, 'address': 'New Delhi',
'age': 99, 'abc': 959}
In [27]: #by using pop () method, it is also possible to update the keys
z['pqr'] = z.pop('abc')
# First it will assign the value of abc key to pqr key
# then remove abc key from the dictionary
print (z)
{1: 56, 2: 68, 3: 434, 4: 500, 5: 98, 6: 1234, 7: 9487, 'address': 'New Delhi',
'age': 99, 'pqr': 959}
{1: 56, 2: 68, 3: 434, 4: 500, 5: 98, 6: 1234, 7: 9487, 'address': 'New Delhi',
'age': 99, 'pqr': 959}
{1: 56, 2: 68, 3: 434, 4: 500, 5: 98, 6: 1234, 7: 9487, 'address': 'New Delhi',
'pqr': 959}
In [30]: # You are specifying the name of the key to remove the item / element
# You want to remove last element without knowing the key
{1: 56, 2: 68, 3: 434, 4: 500, 5: 98, 6: 1234, 7: 9487, 'address': 'New Delhi'}
z.clear ()
print (z)
{}
{}
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-34-79102c64614c> in <module>
----> 1 print (z)