Wednesday, 28 October 2015

Python dictionary



In  python dictionary Values each key is separated from it's values by a colon {:},
each items in dictionary is separated by commas, and all items are enclosed in braces {}.
Keys of a dictionary should be unique. No duplicate. Values can be of any type but keys
should be immutable.




#!/usr/bin/python

dic = {'Code': '001', 'Name': 'Alex', 'Age': 27}
dic1 = {'Code': '001', 'Name': 'Peter', 'Age': 21}


print "dic['Code']: ", dic['Code'] # prints dic['Code']: 001
print "dic['Name']: ", dic['Name'] # prints dic['Name']: Alex
print "dic['Age']: ", dic['Age']   # prints dic['Age']: 27

#example functions and methods used with python dictionary

#compare function compares 2 dictionaries
# cmp returns 1 on mismatch and 0 on match
if cmp(dic,dic1)==1:
  print "Both dictionaries are not equal"
else:
  print "Both dictionaries are equal"

# len function prints the length of dictionaries

print "Length of dic : ",len(dic)

# Removing entry with key 'Code'
del dic['Code']

# Deleting all entries in dic
dic.clear()

# Deleting entire dictionary
del dic

# fromkeys copy keys to another dictionary.
# It has 2 parameters
# 1. seq - the list of values used for the key preparation
# 2. value - optional, if provided then entire element values will be set to this value

dic2 = dic1.fromkeys(dic1,10)

print "dic2['Code']: ", dic2.get('Code') # prints dic2['Code']: 002

# has_keys returns true if the  key exists in the dictionary

if dic1.has_keys('Name'):
 print "The kay name exits'


# keys() Returns list of dictionary keys.

print dic1.keys()

No comments: