【问题标题】:how do I append a dictionary to list that is contained inside another list which is inside a dictionary?如何将字典附加到包含在字典中的另一个列表中的列表中?
【发布时间】:2021-11-03 15:16:39
【问题描述】:

所需输出:

{'students': [courses[{'id2': 2}, {'id3':3}]]}

实施

data={"students": []}
data["students"].append({'courses': []})
i = 2

数据包含字典,学生包含列表,课程包含列表。我想在课程中附加数据。

data["students"]['courses'].append({'id2': i})
print(data)

当我使用上面的代码时,我收到以下错误:TypeError: list indices must be integers or slices, not str

data["students"][0].append({'id2': i})

当我使用上面的代码时,我得到了错误:AttributeError: 'dict' object has no attribute 'append'

data["students"][0]=({'id2': i})

当我使用上面的代码时,它将替换课程列表。 输出:

{'students': [{'id2': 2}]}

如果有人可以帮助我,那将是非常有帮助的。提前致谢!!!

【问题讨论】:

    标签: python json list dictionary nested-lists


    【解决方案1】:

    我刚刚找到了答案:

    data["students"][0]['courses'].append({'id2': i})
    

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    相关资源
    最近更新 更多