在Python中更新并创建一个多维字典

gre*_*rth 7 python dictionary multidimensional-array

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

snippets = {'python': {}, 'text': {}, 'php': {}, 'js': {}}
Run Code Online (Sandbox Code Playgroud)

然后当循环通过JSON我想要将关于该片段的信息添加到它自己的字典中到上面列出的字典.例如,如果我有一个JS片段 - 最终结果将是:

snippets = {'js': 
                 {"title":"Script 1","code":"code here", "id":"123456"}
                 {"title":"Script 2","code":"code here", "id":"123457"}
}
Run Code Online (Sandbox Code Playgroud)

不要混淆水域 - 但是在PHP中使用多维数组我会做以下事情(我正在寻找类似的东西):

snippets['js'][] = array here
Run Code Online (Sandbox Code Playgroud)

我知道我看到一两个人在谈论如何创建一个多维字典 - 但似乎无法追踪在python中向字典添加字典.谢谢您的帮助.

JBe*_*rdo 15

这称为autovivification:

你可以做到 defaultdict

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

d = tree()
d['js']['title'] = 'Script1'
Run Code Online (Sandbox Code Playgroud)

如果想要有列表,你可以这样做:

d = collections.defaultdict(list)
d['js'].append({'foo': 'bar'})
d['js'].append({'other': 'thing'})
Run Code Online (Sandbox Code Playgroud)

default的想法是在访问密钥时自动创建元素.顺便说一句,对于这个简单的案例,你可以简单地做:

d = {}
d['js'] = [{'foo': 'bar'}, {'other': 'thing'}]
Run Code Online (Sandbox Code Playgroud)


pla*_*aux 7

snippets = {'js': 
                 {"title":"Script 1","code":"code here", "id":"123456"}
                 {"title":"Script 2","code":"code here", "id":"123457"}
}
Run Code Online (Sandbox Code Playgroud)

在我看来,你想要一个字典列表.这里有一些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'}]
Run Code Online (Sandbox Code Playgroud)

这清楚了吗?