【问题标题】:python: how to add a key-value pair to the beginning of a nested dictionary?python:如何将键值对添加到嵌套字典的开头?
【发布时间】:2020-08-11 16:03:10
【问题描述】:

我需要添加到嵌套字典的开头。看起来 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'

【问题讨论】:

    标签: python-3.x dictionary nested ordereddictionary


    【解决方案1】:

    内部字典必须是OrderedDict。更改为以下内容:

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

    注意:使用内置名称(例如,dict)是个坏主意。将dict 更改为合适的。

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      相关资源
      最近更新 更多