Zid
Zid

Reputation: 449

Create a new dictionary from existing with new keys

I have a dictionary d, I want to modify the keys and create a new dictionary. What is best way to do this?

Here's my existing code:

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

Is there a better way to map the values using another mapping dictionary or a file where mapping values can be kept.

for eg, something like this:

d3 =  {
        'reference':'VAR_Reference',
        'business_date': 'VAR_date',
        'final_price': 'VAR_TotalPrice'
     }

Appreciate any tips or hints.

Upvotes: 1

Views: 104

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You can use a dictionary comprehension to iterate over your original dictionary, and fetch your new keys from the mapping dictionary

{d3.get(key):value for key, value in d.items()}

You can also iterate over d3 and get the final dictionary (thanks @IcedLance for the suggestion)

{value:d.get(key) for key, value in d3.items()}

Upvotes: 5

Related Questions