Python Objects: Dictionary (dict)




Dictionary or dict is generalization of Lists
In list we use [], while in dict {}

>>> l = ['three', 'five', 'one', 'seven']
>>> l[0] #here 0 in l[0] is called index and 0th index refers to three
'three'
>>> l[1]
'five'
>>> l[2]
'one'
>>> l[3]
'seven'




Now let's see how dictionary can be defined and used. We explicitly define index of data we insert.

dict = {index:data, index:data.... and so on}
Also known as dict = {key:value , key: value .... so on}
We can access the value or data only by using the key or index

>>> d = {3:'three', 5:'five', 1:'one', 7:'seven'}
>>> d[3] # 3 is the index of data 'three'
'three'    # 3 is also called 'key' and 'three' is called 'value'
>>> d[5]
'five'
>>> d[1]
'one'
>>> d[7]
'seven'
>>> d[0] #since we didn't define 0th index in our dict, it returns an error
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    d[0]
KeyError: 0


We can have any datatype as key and any datatype as value.

>>> month = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5: 'May', 6: 'June'}
>>> month[5] #here integers are keys while strings are values.
'May'
>>> month1={'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4,  'May':5,  'June':6}
>>> month1['Jan'] #here integers are values while strings are keys.
1
>>> month2={1:'Jan', 2:'Feb','Mar':3,4:'Apr','May':5,'Jun':6} #here its mixed
>>> month2[2] 
'Feb'
>>> month2['Mar']
3


We can also use _____.keys() and _____.values() to get list of all keys and values seperately.

>>> month.keys()
[1, 2, 3, 4, 5, 6]
>>> month.values()
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June']
>>> month2.keys() 
[1, 2, 'Mar', 4, 'May', 'Jun']
>>> month2.values() 
['Jan', 'Feb', 3, 'Apr', 5, 6]


Inserting into already existing dictionary.
Insertion into already existing dict is done by _____[key] = value

>>>month[7] = 'July'
>>> month
{1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'June',  7: 'July} 
>>> month.keys()
[1, 2, 3, 4, 5, 6, 7]
>>> month.values()
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July']


Keys can also be complex. Here keys are tuples.

>>> myDict = {(1,2):'Twelve', (1,3):'Thirteen'} #(1,2) is a tuple
>>> myDict[(1,2)]
'Twelve'

Related Articles:
Python Objects: Strings and Operations on Strings
Python Objects: Tuples and its use
Python Objects: Lists, its use, Mutation of Lists

Note:
This is a part of what I learn in an online Open Course Ware offered by MIT on edX
Its for my personal reference & also for those who have missed the course.
You too can enroll yourself on edX (if they are still offering the course MITx 6.00x)