将新键添加到嵌套字典中

时间:2016-12-21 14:53:52

标签: python dictionary

JSON:

{'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}

我正在尝试在此列表中添加另一个词典,如下所示:

dict = {'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}
length = len(dict['result'])
print(length)

dict['results'][length+1] = [new_result]

我一直在:

dict['result'][length+1] = [new_result]
IndexError: list assignment index out of range

1 个答案:

答案 0 :(得分:0)

使用列表时,您可以将新项目附加到列表

data_dict['results'].append(new_result)

正如Moses Koledoye在评论中写道,你也可以这样做:

data_dict['results'].extend([new_result])