I want to replace kw's in a dict which may have complex structure (e.g the values may be dicts or lists. Those dicts should also get their kw's replaced and the list elements may be dicts which should also get replaced.) I wrote the following
def replace_kw(obj,replace_this,with_this):
print('object is '+str(obj))
if isinstance(obj,dict):
for k,v in obj.iteritems():
if k==replace_this:
obj[with_this]=obj[replace_this]
del(obj[replace_this])
else:
obj[k] = replace_kw(obj[k],replace_this,with_this)
elif isinstance(obj,list):
for l in obj:
l = replace_kw(l,replace_this,with_this)
return obj
which works on the simple examples I have conme up with but I am curious as to other methods and where this may go wrong. For instance I checked if a keyword can be a dictionary , and it seems the answer is no so that's one place I am not going wrong.
The example I gave was
d = {'data': [{'bbox_xywh': [838, 533, 50, 68], 'object': 'truck'},
{'bbox_xywh': [930, 563, 60, 57], 'object': 'car'},
{'bbox_xywh': [993, 560, 78, 56], 'object': 'car'},
{'bbox_xywh': [997, 565, 57, 39], 'object': 'car'},
{'bbox_xywh': [1094, 542, 194, 126], 'object': 'car'},
{'bbox_xywh': [1311, 539, 36, 74], 'object': 'person'}],
'dimensions_h_w_c': (1200, 1920, 3),
'filename':'/data/jeremy/image_dbs/hls/voc_rio_udacity_kitti_insecam_shuf_no_aug_test/1478020901220540088.jpg'}
replace_kw(d,'bbox_xywh','bbox')
{'data': [{'bbox': [838, 533, 50, 68], 'object': 'truck'},
{'bbox': [930, 563, 60, 57], 'object': 'car'},
{'bbox': [993, 560, 78, 56], 'object': 'car'},
{'bbox': [997, 565, 57, 39], 'object': 'car'},
{'bbox': [1094, 542, 194, 126], 'object': 'car'},
{'bbox': [1311, 539, 36, 74], 'object': 'person'}],
'dimensions_h_w_c': (1200, 1920, 3),
'filename': '/data/jeremy/image_dbs/hls/voc_rio_udacity_kitti_insecam_shuf_no_aug_test/1478020901220540088.jpg'}
which worked as expected