使用新键从现有字典创建新字典

Zid*_*Zid 1 python python-3.x python-3.7

我有一个字典d,我想修改键并创建一个新字典。最好的方法是什么?

这是我现有的代码:

import json

d = json.loads("""{
    "reference": "DEMODEVB02C120001",
    "business_date": "2019-06-18",
    "final_price": 40,
    "products": [
        {
            "quantity": 4,
            "original_price": 10,
            "final_price": 40,
            "id": "123"
        }
    ]
}""")

d2 ={
        'VAR_Reference':d['reference'],
        'VAR_date': d['business_date'],
        'VAR_TotalPrice': d['final_price']
    }
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法可以使用另一个映射字典或可以保留映射值的文件来映射值。

例如:

d3 =  {
        'reference':'VAR_Reference',
        'business_date': 'VAR_date',
        'final_price': 'VAR_TotalPrice'
     }
Run Code Online (Sandbox Code Playgroud)

感谢任何提示或提示。

Dev*_*ngh 5

您可以使用字典理解来迭代原始字典,并从映射字典中获取新密钥

{d3.get(key):value for key, value in d.items()}
Run Code Online (Sandbox Code Playgroud)

您也可以遍历d3并获取最终字典(感谢@IcedLance的建议)

{value:d.get(key) for key, value in d3.items()}
Run Code Online (Sandbox Code Playgroud)