我想将新数据(键,值)存储到嵌套字典中。 但是我不知道如何解决它。
def add(a,b,c,d,container)
container = {} # as database
data ={}
data[a] = [{"first": b, "second": c, "third": d}]
for e in data:
if date[date] not in calendar:
container[date[a]] = {}
container[date[a]].update([{"first": b, "second": c, "third": d})
add(name, 1, 2, hi, container)
add(name1, 2, 1, hi, container)
我看到以下输出:
{name: [{"first": 1, "second": 2, "third":hi }]}
{name1: [{"first": 2, "second": 1, "third":hi }]}
我希望输出为:
{name: [{"first": 1, "second": 2, "third":hi }], name1: [{"first": 2, "second": 1, "third":hi }]}
请帮帮我!
答案 0 :(得分:1)
您正在add
函数中创建本地字典。你看到了吗?
def add(a,b,c,d,container)
container = {} # it's a local new dict
# ...
相反,您应该在函数外部创建字典,否则,您将始终获得仅包含一个键的新字典。例如:
container = {}
def add(a, b, c, d):
container[a] = b
container[c] = d
答案 1 :(得分:0)
我正在创建一个global_dict这是主要的字典,其中存储所有 dict元素发生。 对于给定的问题,如果要连续将数据添加到字典中,并且该字典具有相同的结构,则更好: 是创建一个默认字典,然后在字典中更新值,最后使用update方法将新的小字典添加到主字典中。
def funcion(a,b,c,d, container):
new_dic={a:[{'first':b,"Second":c,"third":d}]}
container.update(new_dic)
funcion('name', 1, 2, 'hi')
funcion('name1', 2, 1,'hi')
print(container)
"""
output
{'name': [{'first': 1, 'Second': 2, 'third': 'hi'}],
'name1': [{'first': 2, 'Second': 1, 'third': 'hi'}]
}
"
答案 2 :(得分:-1)
我最近为此创建了一个模块,并将其发布在github上,它不使用递归,因此对它绝对没有限制。它允许您使用键路径来编辑,添加和删除嵌套字典。这是在stackoverflow上(它将回答您的问题):
,它在github上:
https://github.com/kthewhispers/Nested-Dictionary-Tools-Python/tree/master/src