Home > Enterprise >  How to rename all keys in dict?
How to rename all keys in dict?

Time:09-24

I want to rename the dict keys in python. There are 2 keys 'Curry_Vegetables_Set1 (59).JPG131850' and 'Curry_Vegetables_Set1 (62).JPG104359' which i want to rename with replace1 value. Please help to rename. Below is the dict sample:

file = {'Curry_Vegetables_Set1 (59).JPG131850': {'filename': '1.5_Curry_Vegetables_59.jpg',
  'size': 131850,
  'regions': [{'shape_attributes': {'name': 'polygon',
     'all_points_x': [510, 563,622,],
     'all_points_y': [459,  523, 505,]},
    'region_attributes': {'food': 'curry_vegetable'}}],
  'file_attributes': {}},
 'Curry_Vegetables_Set1 (62).JPG104359': {'filename': '1.5_Curry_Vegetables_62.jpg',
  'size': 104359,
  'regions': [{'shape_attributes': {'name': 'polygon',
     'all_points_x': [471,490,528,],
     'all_points_y': [496,476,493]},
    'region_attributes': {'food': 'curry_vegetable'}}],
  'file_attributes': {}},}

I tried the code below,

for key,value in file.items():
    name = key.split('.')
    num = name[0].split('(')  
    image_num = num[1][:-1]   
    replace1 = '1.5_Curry_Vegetables_' image_num '.' name[1] 
    
    # replace old keys with replace1
    file[replace1] = file[key]

but it gives error as:

RuntimeError: dictionary changed size during iteration

CodePudding user response:

You're not really changing the old keys, you're adding new ones to the same dictionary. You should create a new empty dictionary and add the new key/value pairs to that in the loop.

file2 = {}
for key, value in file.items():
    name = key.split('.')
    num = name[0].split('(')
    image_num = num[1][:-1]
    replace1 = '1.5_Curry_Vegetables_'   image_num   '.'   name[1]

    # replace old keys with replace1
    file2[replace1] = file[key]
    
print(file2)

CodePudding user response:

Inplace:

for oldKey in dictionary:
    name = oldKey .split('.')
    num = name[0].split('(')
    image_num = num[1][:-1]
    newKey = '1.5_Curry_Vegetables_'   image_num   '.'   name[1]
    dictionary[newKey] = dictionary.pop(oldKey)

Or via creating new dict:

def newKeyFromOld(oldKey):
    name = oldKey .split('.')
    num = name[0].split('(')
    image_num = num[1][:-1]
    newKey = '1.5_Curry_Vegetables_'   image_num   '.'   name[1]
    return newKey
{newKeyFromOld(oldKey): value for oldKey, value in dictionary.items()}

CodePudding user response:

for oldKey in dictionary:
    dictionary[newKey] = dictionary[oldKey]
    del dictionary[oldKey]
  • Related