Home > Mobile >  How do I replace keys from a list of dictionaries with values from another dictionary?
How do I replace keys from a list of dictionaries with values from another dictionary?

Time:10-20

I have a list of dicts and a dict.

list_of_dicts = [
{'AssetId':'1234',
 'CreatedById':'02i3s',
 'Billable__c': True},
{'AssetId':'4567',
 'CreatedById':'03j8t',
 'Billable__c':True}
]

dict = {
'AssetKey':'AssetId',
'SourceRowCreatedBy':'CreatedById',
'FlagBillable':'Billable__c'}

I essentially want to replace the keys from list_of_dicts with the keys from dict if the key from list_of_dicts matches with the value from dict. So my output should look like:

new_list_of_dicts = [
{'AssetKey':'1234',
 'SourceRowCreatedBy':'02i3s',
 'FlagBillable': True},
{'AssetKey':'4567',
 'SourceRowCreatedBy':'03j8t',
 'FlagBillable':True}
]

Any help would be greatly appreciated! I am using python 3.9.7. Please let me know if there is anything further I need to provide. Thank you.

CodePudding user response:

First, a note: do not use dict as a variable name. It is a dictionary constructor. So, let's assume your second dictionary is called dict1.

Start by reversing it: swap the keys and the values to form another dictionary.

dict2 = {v: k for k, v in dict1.items()}

Now, for each item in your list, look up the keys in the new dictionary:

[{dict2[k]: v for k,v in d.items()} for d in list_of_dicts]
# [{'AssetKey': '1234', 'SourceRowCreatedBy': '02i3s', 'FlagBillable': True}, 
# {'AssetKey': '4567', 'SourceRowCreatedBy': '03j8t', 'FlagBillable': True}]
  • Related