Python: Changing the Dictionary Keys and values

Here is the post to update the Python’s Dictionary keys and values..

The following steps are for changing the Dictionary keys:

the logic is implemented in the following.

1) take the input of a dictionary which needs to modified the keys.

mainDict = {‘FSTN’:’sum’,’MIDL’:’k’,’ANAME’:’kuch’,’PSTA’:’A’,
‘DOB’:’20081215′,’JOBC’:’1234′}

2) create another dictionary which takes the keys as from the input dictionary (mainDict) keys and values as the what you wanted to replace keys.

keyMap = {‘FSTN’:’FIRST_NAME’,’ANAME’:’LAST_NAME’,’MIDL’:’MIDDLE_NAME’,’DOB’:’BIRTH_DAY’,
‘PSTA’:’STATUS’,’JOBC’:’JOB_CODE’}

3)create final dictionary and loop over the mainDict to replace the keys

changedDict = {}
for key, value in mainDict.items():
changedDict[keyMap[key]] = value

OR

changedDict= dict((keyMap[key], value) for (key, value) in idDict.items())

The following steps are for changing/deleting the Dictionary values:

1)take the input of a dictionary which needs to modified the values.

mainDict = {‘FSTN’:’sum’,’MIDL’:’k’,’ANAME’:’kuch’,’PSTA’:’A’,
‘DOB’:’20081215′,’JOBC’:’1234′}

2)add, delete, and change values in that dictionary

mainDict[“ROOM”] = “HARRIS”
del mainDict[“MIDL”]
mainDict[“JOBC”] = “4321”

I’ll be adding more details about Dictionaries in other post.