我正在尝试创建一个总结另一个字典的字典。我希望只有当关键字与details_dict中的“parent”值匹配时,才会更新summary_dict。然而,我的代码似乎没有按照我的预期访问summary_dict。打印语句显示它继续将内容添加到循环中的第一个可迭代对象中,而不是从summary_dict中获取正确的值。
detail_dict = {'a123': {"data": [1, 2, 3, 4], "parent": "a"},
'a124': {"data": [1, 2, 3, 4, 5], "parent": "a"},
'b123': {"data": [1, 2, 3], "parent": "b"},
'b124': {"data": [1], "parent": "b"}}
summary_dict = dict.fromkeys(["a", "b"], {"data": [],
"data_len": []})
for k, v in detail_dict.iteritems():
summary_dict[v['parent']]["data"].append(v["data"])
summary_dict[v['parent']]["data_len"].append(len(v["data"]))
print "\nMy value is "
print v
print "\nMy summary dictionary now looks like:"
print summary_dict[v['parent']]
我希望得到的字典如下所示:
结果字典应为:
{"a": {"data": [[1, 2, 3, 4], [1, 2, 3, 4, 5]],
"data_len": [4, 5]},
"b": {"data": [[1, 2, 3], [1]],
"data_len": [3, 1]}}