Search code examples
python-3.xdictionarynestedordereddictionary

python: how to add a key-value pair to the beginning of a nested dictionary?


i need to add to the beginning of a nested dictionary. it looks like move_to_end() is the easiest way for us to accomplish this but it seems that i cannot use this in a nested dictionary.

dict = OrderedDict({
  'abdomen' : {"liver":3 , "spleen":1},
  })
dict['abdomen'].update({'stomach':'2'}) 
dict['abdomen'].move_to_end('stomach', last = False)
print(dict['abdomen'])

generates the error: Traceback (most recent call last): File "test.py", line 232, in dict['abdomen'].move_to_end('stomach', last = False) AttributeError: 'dict' object has no attribute 'move_to_end'


Solution

  • The inner dictionary must be an OrderedDict. Change to the following:

    my_dict = OrderedDict({
        'abdomen': OrderedDict({"liver": 3, "spleen": 1}),
    })
    

    Note: Using built-in names (e.g., dict) is a bad idea. Change dict to something suitable.