【问题标题】:Add item to dictionary (array inside of a dictonary?) [duplicate]将项目添加到字典(字典内的数组?)[重复]
【发布时间】:2021-10-09 15:02:06
【问题描述】:
dic = {"t": [{"x": 0}, {"x": 1}, {"x": 2}]}

print(dic)
dic["t"] = dic["t"].append({"x": 3})
print(dic)

实际结果:{'t': None}

想要的结果:{'t': [{'x': 0}, {'x': 1}, {'x': 2}, {"x": 3}]}

可能很简单,我只是不知道要搜索什么。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    append 方法就位,它不输出任何东西(嗯,它输出None)。当您运行 dic["t"] = dic["t"].append({"x": 3}) 时,您将初始列表替换为 None。

    你需要做的:

    dic["t"].append({"x": 3})
    

    完整代码:

    dic = {"t": [{"x": 0}, {"x": 1}, {"x": 2}]}
    print(dic)
    dic["t"].append({"x": 3})
    print(dic)
    

    输出:

    {'t': [{'x': 0}, {'x': 1}, {'x': 2}]}
    {'t': [{'x': 0}, {'x': 1}, {'x': 2}, {'x': 3}]}
    

    【讨论】:

      【解决方案2】:

      append() 返回None,而不是您所期望的应用该方法的列表。变化:

      dic["t"] = dic["t"].append({"x": 3})
      

      收件人:

      dic["t"].append({"x": 3})
      

      另一种选择是执行以下操作:

      dic = {"t": [{"x": 0}, {"x": 1}, {"x": 2}]}
      
      print(dic)
      dic["t"] += [{"x": 3}]
      print(dic)
      

      【讨论】:

        【解决方案3】:

        尝试只执行dic["t"].append({"x":3}),因为append 更新列表但返回None,因此您的新值将是None。相反,只需更新值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-14
          相关资源
          最近更新 更多