Dictionary

Dictionary is an unordered set of key and value pair.

It is an container that contains data, enclosed within curly braces.

The pair i.e., key and value is known as item.

The key passed in the item must be unique.

The key and the value is separated by a colon(:). This pair is known as item. Items are separated from each other by a comma(,). Different items are enclosed within a curly brace and this forms Dictionary.

eg:

data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print(data)

Output:

>>>  
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
>>>

Dictionary is mutable i.e., value can be updated.

Key must be unique and immutable. Value is accessed by key. Value can be updated while key cannot be changed.

Dictionary is known as Associative array since the Key works as Index and they are decided by the user.

eg:

plant={}
plant[1]='Ravi'
plant[2]='Manoj'
plant['name']='Hari'
plant[4]='Om'
print plant[2]
print plant['name']
print plant[1]
print plant  

Output:

>>>
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name': 'Hari'}
>>>

Accessing Values

Since Index is not defined, a Dictionaries value can be accessed by their keys.

Syntax:

[key]

Eg:

data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
print "Id of 1st employer is",data1['Id']
print "Id of 2nd employer is",data2['Id']
print "Name of 1st employer:",data1['Name']
print "Profession of 2nd employer:",data2['Profession']

Output:

>>>
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer is Trainer
>>>

Updation

The item i.e., key-value pair can be updated. Updating means new item can be added. The values can be modified.

Eg:

data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
data1['Profession']='Manager'
data2['Salary']=20000
data1['Salary']=15000
print data1
print data2

Output:

>>>
{'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name': 'Suresh'}
{'Salary': 20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}
>>>

Deletion

del statement is used for performing deletion operation.

An item can be deleted from a dictionary using the key.

Syntax:

del  [key]

Whole of the dictionary can also be deleted using the del statement.

Eg:

data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102]
print data
del data
print data   #will show an error since dictionary is deleted.

Output:

>>>
{100: 'Ram', 101: 'Suraj'}

Traceback (most recent call last):
  File "C:/Python27/dict.py", line 5, in
   print data
NameError: name 'data' is not defined
>>>