Python Tutorial

Wednesday, August 18, 2010

Python : Dictionary

'''
    This code use dictionary syntax
'''
myDictionary={"name":"anyName","age":500,"subject":"CSE"}

'''
   insert new data into dictionary
'''
myDictionary["address"]="dhaka"
'''
    access index of a dictionary
    if there is no data it will raise an exception
'''
print myDictionary["age"]

'''
   find dictionary length
'''

print "Dictionary Length : ",len(myDictionary)

'''
   access all dictionary data
'''
for n in myDictionary:
    print n ," ", myDictionary[n]

myDictionary["temp"]="data"
print myDictionary
'''
   delete dictionary item
'''
del myDictionary["temp"]
print myDictionary

'''
   compare two dictionary
   if two dictionary have same content return 0
'''
newDictionary=myDictionary
print cmp(myDictionary,newDictionary)
'''
   get all dictioany data as a tupple
'''

myTupple=()
myTupple=myDictionary.items()
'''
   syntax of access tupple
'''
print myTupple
print myTupple[0]
print myTupple[0][0]
'''
   clear dictionary
'''
myDictionary.clear()

print myTupple



Output:

500
Dictionary Length :  4
age   500
address   dhaka
name   anyName
subject   CSE
{'age': 500, 'address': 'dhaka', 'name': 'anyName', 'temp': 'data', 'subject': 'CSE'}
{'age': 500, 'address': 'dhaka', 'name': 'anyName', 'subject': 'CSE'}
0
[('age', 500), ('address', 'dhaka'), ('name', 'anyName'), ('subject', 'CSE')]
('age', 500)
age
[('age', 500), ('address', 'dhaka'), ('name', 'anyName'), ('subject', 'CSE')]

0 comments:

Post a Comment