繁体   English   中英

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

[英]Update and create a multi-dimensional dictionary in Python

我正在解析存储各种代码片段的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中使用多维数组我会做以下事情(我正在寻找类似的东西):

snippets['js'][] = array here

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

这称为autovivification

你可以用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'})

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

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

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'}]

这清楚了吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM