hi I can change dictionary values but I can't figure out to change the keys..

here is the scenario I want..

A dictionary is coming like this {'fstn':'Tim','lstn':'Parker','mdl':'W','dob':'19801201'}
now I need to change to
{'FIRST_NAME':'Tim','LAST_NAME':'Parker','MIDDLE_NAME':'W', 'BIRTH_DATE':'19801201'}

please help me to change the keys..

Recommended Answers

All 2 Replies

Use a third dict

D = {'fstn':'Tim','lstn':'Parker','mdl':'W','dob':'19801201'}
remap = {'fstn':'FIRST_NAME','lstn':'LAST_NAME','mdl':'MIDDLE_NAME','dob':'BIRTH_DAY'}

otherD = dict((remap[key], value) for (key, value) in D.items())

print(otherD)

"""my output -->
{'BIRTH_DAY': '19801201', 'FIRST_NAME': 'Tim', 'LAST_NAME': 'Parker', 'MIDDLE_NAME': 'W'}
"""

Use a third dict

D = {'fstn':'Tim','lstn':'Parker','mdl':'W','dob':'19801201'}
remap = {'fstn':'FIRST_NAME','lstn':'LAST_NAME','mdl':'MIDDLE_NAME','dob':'BIRTH_DAY'}

otherD = dict((remap[key], value) for (key, value) in D.items())

print(otherD)

"""my output -->
{'BIRTH_DAY': '19801201', 'FIRST_NAME': 'Tim', 'LAST_NAME': 'Parker', 'MIDDLE_NAME': 'W'}
"""

OOW.. gr8 and thank you Gribouillis for your tips, it works for me..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.