首页 > 解决方案 > 如何在for循环中将数据添加到字典

问题描述

我想知道如何在 for 循环中更新具有某些结果的字典。

目前,我有这样的事情:

some_dict = {}
result = call_to_some_method(some_data)
some_dict.update(json.loads(result))

我现在将代码更改如下:

some_dict = {}
for i in ["cat","cat2","zeta"]:
    result = call_to_some_method(some_data)
    ## Update the result for each iteration

有人可以帮忙吗,这样最后我会像以前一样返回字典

标签: pythondictionary

解决方案


我认为您想要做的是以下内容:

some_dict = {}
for i in ["cat","cat2","zeta"]:
    result = call_to_some_method(i)
    some_dict[i] = result # This updates the dictionary

推荐阅读