Python dictionary data type – dict() methods explained

Python Dictionary are useful data type in Python which allows programmer to define it’s own index to access the value of the object.So each element in dictionaries comes with ‘key:value‘ pair.By only using the ‘key’ we can access the ‘value’ of the object.

There are quite a few ways to create a dictionary object.Here we will see how to create dictionary in five ways.

i)Using curly braces

:The first way is the simplest way to create a dictionary.

>>> dic={ 10:'A' , 20:'B' , 30:'D' , 40:'New' }
>>> dic1={ 'New':34 , 'text':45 , 'S':890 , 90:'6789' }

Do you see each element of the ‘dic’ and ‘dic1’ object has a ‘key:value’ pair and note the colon(‘:’) separating them.

ii)Using the method dict()

:Here the method dict() is used in creating the dictionary.

>>> a=dict(A=1253, Z=-1939 , b=920) #note '=' is used instead of ':'
>>> b=dict('A'=90)
SyntaxError: keyword can't be an expression

Note with this method we cannot create a dictionary that has string as a key as you can see from the above example.

iii)Using the methods dict() and zip()

:Here we will use the methods dict() and zip() to create a dictionary.The disadvantage of this method is that we can create dictionary containing only two elements at a time.

>>> c = dict(zip(['Text', 'Z'], [14994, '64774040']))
>>> d=dict( zip(['A',4747], [234 ,'Text']) )
>>> e=dict( zip([34, 89] , [34,90] , ['S','AA']) ) #error!!
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    e=dict( zip([34, 89] , [34,90] , ['S','AA']) )
ValueError: dictionary update sequence element #0 has length 3; 2 is required

Trying to create a dictionary with more than 2 length(elements) gives error her.

Note the elements inside the first square bracket are the keys and the elements inside the second square bracket represent the value of the each of the corresponding key in the first square bracket.More about this in the next section.

iv)Using the method dict() and square bracket([])

:Here the key and value pair is wrap in a bracket which is placed inside the square bracket which is an argument of the dict() method.

>>> d = dict([('A', 1), ('Z', -1) , (45 , 980)])
>>> d1= dict( [(657 ,'Text') , (56754,8595) , ('A' , 758589) , ("C++" , 'Candcpluplus is the best')] )

v)Using the method dict() and the first method(shown above)

:Here the dictionary ‘key:value’ pair is placed inside the curly braces which is an argument of the dict() method.So this method combines using the first method shown above plus the dict() function.

>>> e = dict({'Z': -1, 'A': 1 , 'Python':'Language' , 'C++':'language'})

Among all the methods discuss above for creating a dictionary the first method is the simplest one.

To create an empty dictionary use the curly braces without any element.

>>> d={}

There is one more way to create a dictionary using the method fromkeys(),you can visit the link given below to know more.

Link : Dictionary fromkeys() method

The next section shows how to access the dictionary.


Accessing the dictionary

Accessing the dictionary is very simple.We will use the object and the key will be use an index inside the square bracket([]).Note if you pass any key that does not exist int eh dictionary you will get an error.

Let us see how to access each of the value created using the the different method above.

>>> #1st method
>>> dic={ 10:'A' , 20:'B' , 30:'D' , 40:'New' }
>>>  dic[10]
'A'
>>> dic[40]
'New'
>>> #2nd method
>>> a=dict(A=1253, Z=-1939 , b=920)
>>> a['A']
1253
>>> a['Z']
-1939
>>> #3rd method
>>> c = dict(zip(['Text', 'Z'], [14994, '64774040']))
>>> c['Text']
14994
>>> c['Z']
'64774040'
>>> #4th method
>>> d = dict([('A', 1), ('Z', -1) , (45 , 980)])
>>> d['A']
1
>>> d[45]
980
>>> #5th method
>>> e = dict({'Z': -1, 'A': 1 , 'Python':'Language' , 'C++':'language'})
>>> e['C++']
'language'
>>> e['Python']
'Language'

Let us now try to access a key which does not exist.

>>> dic={ 10:'A' , 20:'B' , 30:'D' , 40:'New' }
>>> dic[1000]
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    dic[1000]
KeyError: 1000
>>> dic['a']
Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    dic['a']
KeyError: 'a'

One of the strange behavior you will notice while using the 3th method i.e. creating dictionary with dict() and zip() method is if you pass two string as the zip() method’s argument without any square bracket then each of the character in the first string is treated as the key and the corresponding character in the second string as the value.Consider the code below.

>>> d1 = dict(zip('HeLlo', 'Maker'))
>>> d1['H'] #1st character in 1st string
'M'
>>> d1['L'] #3rd character in 1st string
'k'
>>> d1['o'] #last character in 1st string
'r'

The value of d1[‘H’](‘H’ as key) is ‘M’ ,the value of d1[‘L’](‘L’ as key) is ‘K’ and the value of d1[‘o’](‘o’ as key) is ‘r’.Do you see the pattern?



Leave a Reply

Your email address will not be published. Required fields are marked *