python-3.x - 如何用另一个字典中的值替换字典列表中的键?
问题描述
我有一个字典列表和一个字典。
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
键。所以我的输出应该是这样的:dict
list_of_dicts
dict
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。如果我需要提供任何进一步的信息,请告诉我。谢谢你。
解决方案
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}]
推荐阅读
- visual-studio-code - 如何强制 VSCode 只打开一次文件?
- c# - “包含”操作 EntityFramework WPF App
- github - 如何在 GitHub Desktop 中“取消分叉”?
- xml - GPO 使用 XML 报告缺失数据
- mysql - 在针对 MySQL 数据库的 Ruby on Rails 单元测试更新模型中给出错误:ActiveRecord::ValueTooLong
- java - 当我尝试在 Spring Mvc 中插入背景图像时,它没有出现
- python - Python:使用 Pyscipopt 进行线性规划
- visual-studio - 我可以为 git bash 和 Visual Studio 2019 设置不同的 difftools 吗?
- python - 使用烧瓶时连接到 postgresql 时出错
- c# - 当传入的通知具有不同的 JSON 结构时,如何在 MVC 5 中编写控制器方法?