我想在Python中合并两个或多个字典。我想要一本普通的字典,里面还有另一本字典。
common_dic = {}
for y in range(1,3):
for i in range(1,4):
tmp_dic = {}
if i is 1:
tmp_dic["one"] = i
if i is 2:
tmp_dic["two"] = i
if i is 3:
tmp_dic["three"] = i
我打印common_dic
时的预期结果是
({'one': 1, 'two': 2, 'three': 3}, {'one': 1, 'two': 2, 'three': 3})
当我使用json格式输出时
[
{
"one": 1,
"two": 2,
"three": 3
},
{
"one": 1,
"two": 2,
"three": 3
}
]
有什么想法吗?
答案 0 :(得分:1)
基于新编辑的解决方案。 我们正在创建字典并将其附加到列表中。因此,结果是字典列表。
common_dic = []
for y in range(1,3):
tmp_dic = {}
for i in range(1,4):
if i is 1:
tmp_dic["one"] = i
if i is 2:
tmp_dic["two"] = i
if i is 3:
tmp_dic["three"] = i
common_dic.append(tmp_dic)
print(common_dic)
# Output: [{'one': 1, 'two': 2, 'three': 3}, {'one': 1, 'two': 2, 'three': 3}]