用Python更新并创建多维字典

用Python更新并创建多维字典,python,dictionary,multidimensional-array,Python,Dictionary,Multidimensional Array,我正在解析存储各种代码片段的JSON,我首先构建了这些代码片段使用的语言词典: snippets = {'python': {}, 'text': {}, 'php': {}, 'js': {}} 然后,当在JSON中循环时,我希望将有关代码片段的信息添加到上面列出的字典中。例如,如果我有一个JS代码段,最终结果将是: snippets = {'js': {"title":"Script 1","code":"code here", "id":"123456

我正在解析存储各种代码片段的JSON,我首先构建了这些代码片段使用的语言词典:

snippets = {'python': {}, 'text': {}, 'php': {}, 'js': {}}
然后,当在JSON中循环时,我希望将有关代码片段的信息添加到上面列出的字典中。例如,如果我有一个JS代码段,最终结果将是:

snippets = {'js': 
                 {"title":"Script 1","code":"code here", "id":"123456"}
                 {"title":"Script 2","code":"code here", "id":"123457"}
}
不是为了混淆视听,而是在处理多维数组的PHP中,我只需执行以下操作(我正在寻找类似的操作):

我知道我看到一两个人在谈论如何创建多维字典,但似乎没有找到在python中向字典添加字典的方法。谢谢你的帮助

来自

snippets = {'js': 
                 {"title":"Script 1","code":"code here", "id":"123456"}
                 {"title":"Script 2","code":"code here", "id":"123457"}
}
在我看来,你好像想要一份字典清单。下面是一些python代码,希望能得到您想要的结果

snippets = {'python': [], 'text': [], 'php': [], 'js': []}
snippets['js'].append({"title":"Script 1","code":"code here", "id":"123456"})
snippets['js'].append({"title":"Script 1","code":"code here", "id":"123457"})
print(snippets['js']) #[{'code': 'code here', 'id': '123456', 'title': 'Script 1'}, {'code': 'code here', 'id': '123457', 'title': 'Script 1'}]
这清楚吗?

这叫做:

您可以使用
defaultdict

def tree():
    return collections.defaultdict(tree)

d = tree()
d['js']['title'] = 'Script1'
如果您想创建列表,您可以执行以下操作:

d = collections.defaultdict(list)
d['js'].append({'foo': 'bar'})
d['js'].append({'other': 'thing'})
defaultdict的想法是在访问键时自动创建元素。顺便说一句,对于这种简单的情况,您只需执行以下操作:

d = {}
d['js'] = [{'foo': 'bar'}, {'other': 'thing'}]

这就是我要建议的,但从他的第二个代码片段来看,他似乎希望“js”返回一个dict列表。@placeybordeaux我不太喜欢,但我很确定他们的“Array”对象可能会根据月球位置或类似的东西表现为list或dict……我不喜欢PHP,但我指的是
snippets={'js':{“id”:“3”}{“id”:“2”}
,看起来他想要一个连接到js、文本、python等的DICT列表。我喜欢defaultdicts,甚至更喜欢递归定义的defaultdicts,但是看起来他们不会为他想要的东西工作。@placeybordeaux我以为他无意中贴了两次线。。。可能一个
defaultdict(list)
会解决这个问题是的,我确实需要多个字典,所以我会看看defaultdict(list),如果你想提供一个这样的例子那就太好了。看起来@placeybordeaux的答案可以满足我的要求,但我喜欢在学习一门新语言时学习不同的方法。谢谢。酷,你需要更多的解释吗?如果答案能解决你的问题,请记住接受它。
d = {}
d['js'] = [{'foo': 'bar'}, {'other': 'thing'}]