I have a dictionary in Python (uglyDict
) that has some really un-cool key names. I would like to rename them based on values from another dictionary (keyMapping
). Here's an example of the dictionaries:
uglyDict = { "ORDER_NUMBER": "6492", "Ship To - Name": "J.B Brawls", "Ship To - Address 1": "42 BAN ROAD", "Ship To - City": "Jimville", "Ship To - State": "VA", "Ship To - Postal Code": "42691" } keyMapping = { "Market - Store Name": "WSCUSTOMERID", "Ship To - Name": "ShipToCompany", "Ship To - Country": "ShipToCountryCode", "Ship To - Postal Code": "ShipToZipcode", "Ship To - City": "ShipToCity", "Date - Order Date": "OrderDate", "Gift - Message": "SpecialInstructions", "Customer Email": "ShipToEmail", "Ship To - Address 2": "ShipToAddress2", "Ship To - Address 1": "ShipToAddress1", "Ship To - Phone": "ShipToPhoneNum", "Order - Number": "ORDER_NUMBER", "Ship To - State": "ShipToState", "Carrier - Service Selected": "ShipMethod", "Item - SKU": "PRODUCT_NUMBER", "Item - Qty": "Quantity" }
Here is my code so far to rename uglyDict
's keys:
prettyDict = {} for mkey, mval in keyMapping.items(): for ukey in uglyDict.keys(): if mkey == ukey: prettyDict[mval] = uglyDict[mkey] print(prettyDict)
The code works as desired, and prints the dictionary with renamed keys as shown below:
{'ORDER_NUMBER': '6492', 'ShipToCompany': 'J.B Brawls', 'ShipToAddress1': '42 BAN ROAD', 'ShipToCity': 'Jimville', 'ShipToState': 'VA', 'ShipToZipcode': '42691'}
My question is, is there any more efficient/more Pythonic way to do this? Preferably one where I don't have to loop over the keys of both dictionaries. I am using this code with much larger dictionaries and performance is needed.
Any insight is welcome!