【问题标题】:Unable to append object to nested list无法将对象附加到嵌套列表
【发布时间】:2015-09-28 00:57:09
【问题描述】:

我有一个如下所示的 JSON 对象:

[
  {
    "modulename": "module1",
    "functions": [
      {
        "functionname": "get",
        "function": "function1"
      },
      {
        "functionname": "delete",
        "function": "function2"
      }
    ]
  }
]

我的代码如下所示:

modules = []

for functionname in function_dictionary:

    modulename = function_dictionary[function][1]
    func = function_dictionary[function][0]


    module_func = {"modulename" : modulename, "functions" : [{"functionname" : functionname, "function" : func}]}

    found = False
    for module in modules:
        if module["modulename"] == modulename:
            module["modulename"]["functions"].append({"functionname" : functionname, "function" : func}) #error here
            found = True
            break

    if not found:
        modules.append(module_func)

但是我不断收到string indices must be integers, not str 错误。

我不知道为什么会这样。

我将其解读为“将对象 {"functionname" : function, "function" : func} 附加到位于 module["modulename"]["functions"] 的列表中

欢迎任何建议!

【问题讨论】:

  • 替换 module["modulename"]["functions"].appendmodule["functions"].append ; module["modulename"] 确实是一个字符串

标签: python json list dictionary multidimensional-array


【解决方案1】:

愚蠢的我,是我的错字:

module["modulename"]["functions"].append({"functionname" : functionname, "function" : func}) #error here

应该是:

module["functions"].append({"functionname" : function, "function" : func})

我误读了我自己的对象,虽然 functions 列表嵌套在 modulename 中,但实际上它们处于同一级别。

【讨论】:

    猜你喜欢
    • 2017-11-17
    • 2021-12-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    相关资源
    最近更新 更多