Home > Blockchain >  JSON rename nested dictionary name
JSON rename nested dictionary name

Time:10-07

Im trying to edit the nested dictionary name i want to run in for loop this json file to create it 5 times in different name

{
  "fruits": {
      "color": "green",
      "fruit": "apple",
  }
}

How can i change the fruits to fruits1, fruits2, fruits3 .... etc. I dont want to change the inside of the dictionary only the main name (fruits every time on foor loop)

filename = "test.json"

for i in range(1,5 1):
    with open(filename, 'r') as params:
         data = json.load(params, object_pairs_hook=OrederedDict)

    for key in data.items()
        print(key[0]) # its print fruits
        key[0] = "fruits" str(i)

    with open(filename, 'w') as json_file:
         json.dump(data,json_file)

Example (after):

{
  "fruits1": {
      "color": "green",
      "fruit": "apple",
  }
}

CodePudding user response:

You cannot change the name of a key in a Python dictionary. What you can do is choose another name for an existing key, assign the original key's value to that then delete (del) the original key.

Given your sample data, you could do this:

D = {
  "fruits": {
      "color": "green",
      "fruit": "apple",
  }
}

D['fruits1'] = D['fruits']
del D['fruits']
print(D)

CodePudding user response:

you can use .pop()

with sample data you gives to us, you could do this:

a = {
  "fruits": {
      "color": "green",
      "fruit": "apple",
  }
}

a['fruits1'] = a.pop('fruits')
print(a)
  • Related