Guest User

Untitled

a guest
Jan 25th, 2026
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | Source Code | 0 0
  1. import pprint
  2.  
  3. def rename_key_nested(dictionary, old_key, new_key, max_level, current_level=0):
  4.     if current_level == 1:
  5.         print("**********Line 5",)
  6.         pprint.PrettyPrinter(width=20, sort_dicts=False).pprint(dict4)
  7.         print("**********Line 5", )
  8.         print("Line 8 Args> old_key: {0}, new_key: {1}".format(old_key, new_key))
  9.     global inner_counter
  10.     inner_counter = 0
  11.     outer_counter = 0
  12.     for key in list(dictionary.keys()):
  13.         outer_counter += 1
  14.         if isinstance(dictionary[key], dict):
  15.             rename_key_nested(dictionary[key], old_key, new_key, max_level, current_level + 1)
  16.         # Change the key only if we're at the second level (level == 1)
  17.         elif key == old_key and current_level == max_level:
  18.             print("Line 18 new_key: {0}".format(new_key))
  19.             dictionary[new_key] = dictionary.pop(old_key)
  20.             inner_counter += 1
  21.             break # doesn't work
  22.     print("*****************************"
  23.           "\nLine 22 outerC: {0}, innerC: {1}"
  24.           "\n*******************************".format(inner_counter, outer_counter))
  25.  
  26. dict3 = {'Car':   {'Sports':    '3k',
  27.                   'Van':        '6k'},
  28.         'Truck': {'Semi-Truck': '80k',
  29.                    'Coach Bus': '50k'}
  30. }
  31.  
  32. dict4 = {'Car': {'Sports': '3k',
  33.                  'Van': '6k',
  34.                  'SUV-Crossover': '4k'},
  35.         'Truck': {'Semi-Truck': '80k',
  36.            'Coach Bus': '50k'}}
  37.  
  38.  
  39. #call function
  40. print("\nChange key from 'Sports', to 'Sports Compact\n")
  41. rename_key_nested(dict4, 'Sports', 'Sports-Compact', 1)
  42. print("Inner counter value: {0}\n".format(inner_counter))     # Should be 1 not 3
  43. pprint.PrettyPrinter(width=20, sort_dicts=False).pprint(dict4)
Advertisement
Add Comment
Please, Sign In to add comment