python: 如何在嵌套字典的开头添加键值对?
python: how to add a key-value pair to the beginning of a nested dictionary?
我需要添加到嵌套字典的开头。看起来 move_to_end() 是我们完成此操作的最简单方法,但似乎我不能在嵌套字典中使用它。
dict = OrderedDict({
'abdomen' : {"liver":3 , "spleen":1},
})
dict['abdomen'].update({'stomach':'2'})
dict['abdomen'].move_to_end('stomach', last = False)
print(dict['abdomen'])
生成错误:
追溯(最近一次通话):
文件 "test.py",第 232 行,位于
dict['abdomen'].move_to_end('stomach', last = False)
AttributeError: 'dict' 对象没有属性 'move_to_end'
内部字典必须是 OrderedDict
。更改为以下内容:
my_dict = OrderedDict({
'abdomen': OrderedDict({"liver": 3, "spleen": 1}),
})
注意:使用内置名称(例如,dict
)不是一个好主意。将 dict
更改为合适的内容。
我需要添加到嵌套字典的开头。看起来 move_to_end() 是我们完成此操作的最简单方法,但似乎我不能在嵌套字典中使用它。
dict = OrderedDict({
'abdomen' : {"liver":3 , "spleen":1},
})
dict['abdomen'].update({'stomach':'2'})
dict['abdomen'].move_to_end('stomach', last = False)
print(dict['abdomen'])
生成错误: 追溯(最近一次通话): 文件 "test.py",第 232 行,位于 dict['abdomen'].move_to_end('stomach', last = False) AttributeError: 'dict' 对象没有属性 'move_to_end'
内部字典必须是 OrderedDict
。更改为以下内容:
my_dict = OrderedDict({
'abdomen': OrderedDict({"liver": 3, "spleen": 1}),
})
注意:使用内置名称(例如,dict
)不是一个好主意。将 dict
更改为合适的内容。