Friday, June 12, 2015

To interchange key value pairs of a dictionary object in Python

dt = {'a': '1', 'b' : '2', 'c': '3', 'd': '4'}
print "Original dictionary:", dt
dt1 = {}
for (x, y) in dt.iteritems():
(x,y) = (y,x)
dt1.update(dict([(x,y)]))
print "After interchanging key value pairs:", dt1

Output:

Original dictionary: {'a': '1', 'c': '3', 'b': '2', 'd': '4'}
After interchanging key value pairs: {'1': 'a', '3': 'c', '2': 'b', '4': 'd'}

No comments:

Post a Comment