Python Update all values of just the key name in dictionary

Question:

I am trying to update the key name in dictionary using python.

I tried a for loop like below, but it was basically overriding the values and not saving the values in a list format.

How can I recursively add it using a for loop, or is there any better approach for it?

for lstr_document_object in pdct_input_body["Input"]:
    lstr_document_object["DocumentType"] = lstr_document_object["ObjectType"]
    lstr_document_object["DocumentFormat"] = lstr_document_object["ObjectFormat"]
    lstr_document_object["DocumentSourceFileName"] = 
    lstr_document_object["ObjectSourceFileName"]
  • For directly updating the value I tried using, but it resulted in no updation.
sample_dict['DocumentType'] = sample_dict.pop('ObjectType')
  • Sample Input
{
  "Input": [
    {
      "ObjectType": "Document",
      "ObjectFormat": "pdf",
      "ObjectSourceFileName": "Mr.Dave_ICICI.pdf"
    },
    {
      "ObjectType": "Document",
      "ObjectFormat": "pdf",
      "ObjectSourceFileName": "Mr.Dave_HDFC.pdf"
    }
  ],
  "Source": "Client",
  "ClientCode": "CL"
}
  • Desired Output
{
  "Input": [
    {
      "DocumentType": "Document",
      "DocumentFormat": "pdf",
      "DocumentSourceFileName": "Mr.Dave_ICICI.pdf",
      "UUID": "<generated-uuid>"
    },
    {
      "DocumentType": "Document",
      "DocumentFormat": "pdf",
      "DocumentSourceFileName": "Mr.Dave_HDFC.pdf",
      "UUID": "<generated-uuid>"
    }
  ],
  "Source": "Client",
  "ClientCode": "CL"
}
Asked By: donny

||

Answers:

Perhaps you can try json modul, turn the dictionary to a json string, replace the key names, and then turn it back to a dictionary, e.g.

import json

adict = {'a':1, 'b':2}

>>> adict

{'a': 1, 'b': 2}

jsonstr = json.dumps(adict)

adict = json.loads(jsonstr.replace('a', 'c'))

>>> adict

{'c': 1, 'b': 2}
Answered By: Ancient Ghost

Something like this might do the trick:

data = {
  "Input": [
    {
      "ObjectType": "Document",
      "ObjectFormat": "pdf",
      "ObjectSourceFileName": "Mr.Dave_ICICI.pdf"
    },
    {
      "ObjectType": "Document",
      "ObjectFormat": "pdf",
      "ObjectSourceFileName": "Mr.Dave_HDFC.pdf"
    }
  ],
  "Source": "Client",
  "ClientCode": "CL"
}


def replacer(x):
     return { k.replace("Object", "Document"): v for k,v in x.items()}
     
data["Input"] = [replacer(x) for x in data["Input"]]

It doesn’t strictly "update", but replaces the "Input" part with a newly generated one, but I think it does what you wanted.

Answered By: Mattias Nilsson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.