0

I am trying to rename keys of json data but I don't seem to get what I am looking for. Could you please point the issue?

import json

if __name__ == '__main__':

    json_data = [
        {
            "Aa": "A1 value",
            "Ab": "A2 Value",
            "Ac": "0",
            "Ad": "245",
            "Ae": "some value"
        },
        {
            "Aa": "A1 value2",
            "Ab": "A2 Value2",
            "Ac": "1",
            "Ad": "225",
            "Ae": "some value2"
        }
        ]

    vcounter = 1
    for item in json_data:      
        for oldKey,v in item.items():
            newKey = 'X'+str(vcounter)
            #print(newKey)
            item[newKey] = item.pop(oldKey)
            vcounter += 1
        print('Item:'+str(item))
        print('-----------------')
        vcounter = 1

output

Item:{'Ab': 'A2 Value', 'X4': 'some value', 'X5': 'A1 value', 'X6': '0', 'X7': '245'}
-----------------
Item:{'Ab': 'A2 Value2', 'X4': 'some value2', 'X5': 'A1 value2', 'X6': '1', 'X7': '225'}
-----------------

Expected output Keys to be renamed as X1 to the length of the items in the list. In this case it's X1 to X5

Item:{'X2': 'A2 Value', 'X5': 'some value', 'X1': 'A1 value', 'X3': '0', 'X4': '245'}
-----------------
Item:{'X2': 'A2 Value2', 'X5': 'some value2', 'X1': 'A1 value2', 'X3': '1', 'X4': '225'}
-----------------

1 Answer 1

1

Providing that you're using Python 3.7+, where dict keys are ordered, you can use a dict comprehension to iterate over an enumeration of dict values to build a new dict with the new keys that are generated by concatenating 'X' with the enumerated index:

[{'X%s' % i: v for i, v in enumerate(d.values(), 1)} for d in json_data]

This returns:

[{'X1': 'A1 value',
  'X2': 'A2 Value',
  'X3': '0',
  'X4': '245',
  'X5': 'some value'},
 {'X1': 'A1 value2',
  'X2': 'A2 Value2',
  'X3': '1',
  'X4': '225',
  'X5': 'some value2'}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.