我正在解析存储各种代码片段的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中将字典添加到字典中。谢谢你的帮助。
发布于 2013-02-14 11:59:26
这称为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'})defaultdict的想法是在访问key时自动创建元素。顺便说一句,对于这个简单的例子,你可以简单地这样做:
d = {}
d['js'] = [{'foo': 'bar'}, {'other': 'thing'}]发布于 2013-02-14 11:59:11
从…
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'}]这样说清楚了吗?
https://stackoverflow.com/questions/14867496
复制相似问题