首页 > 解决方案 > 如何用另一个字典中的值替换字典列表中的键?

问题描述

我有一个字典列表和一个字典。

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

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

如果来自的键与来自的值匹配,我基本上想用来自的键替换list_of_dicts键。所以我的输出应该是这样的:dictlist_of_dictsdict

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

在@DYZ 的帮助下,上述问题得以解决。谢谢!

编辑:现在我遇到了一种情况,我有一个看起来像这样的字典列表:

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

我将如何遍历这些来更新它们?

任何帮助将不胜感激!我正在使用 python 3.9.7。如果我需要提供任何进一步的信息,请告诉我。谢谢你。

标签: python-3.xlistdictionary

解决方案


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}]

推荐阅读