Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pprint
- def rename_key_nested(dictionary, old_key, new_key, max_level, current_level=0):
- if current_level == 1:
- print("**********Line 5",)
- pprint.PrettyPrinter(width=20, sort_dicts=False).pprint(dict4)
- print("**********Line 5", )
- print("Line 8 Args> old_key: {0}, new_key: {1}".format(old_key, new_key))
- global inner_counter
- inner_counter = 0
- outer_counter = 0
- for key in list(dictionary.keys()):
- outer_counter += 1
- if isinstance(dictionary[key], dict):
- rename_key_nested(dictionary[key], old_key, new_key, max_level, current_level + 1)
- # Change the key only if we're at the second level (level == 1)
- elif key == old_key and current_level == max_level:
- print("Line 18 new_key: {0}".format(new_key))
- dictionary[new_key] = dictionary.pop(old_key)
- inner_counter += 1
- break # doesn't work
- print("*****************************"
- "\nLine 22 outerC: {0}, innerC: {1}"
- "\n*******************************".format(inner_counter, outer_counter))
- dict3 = {'Car': {'Sports': '3k',
- 'Van': '6k'},
- 'Truck': {'Semi-Truck': '80k',
- 'Coach Bus': '50k'}
- }
- dict4 = {'Car': {'Sports': '3k',
- 'Van': '6k',
- 'SUV-Crossover': '4k'},
- 'Truck': {'Semi-Truck': '80k',
- 'Coach Bus': '50k'}}
- #call function
- print("\nChange key from 'Sports', to 'Sports Compact\n")
- rename_key_nested(dict4, 'Sports', 'Sports-Compact', 1)
- print("Inner counter value: {0}\n".format(inner_counter)) # Should be 1 not 3
- pprint.PrettyPrinter(width=20, sort_dicts=False).pprint(dict4)
Advertisement
Add Comment
Please, Sign In to add comment