在Python中更新和创建多维字典
我正在解析一个存储各种代码片段的JSON数据,首先我需要建立一个字典,里面记录这些代码片段使用的编程语言:
snippets = {'python': {}, 'text': {}, 'php': {}, 'js': {}}
然后在遍历这个JSON的时候,我想把每个代码片段的信息添加到上面那个字典里,形成自己的字典。比如,如果我有一个JavaScript的代码片段,最终的结果应该是这样的:
snippets = {'js':
{"title":"Script 1","code":"code here", "id":"123456"}
{"title":"Script 2","code":"code here", "id":"123457"}
}
为了不让事情变得复杂,我在PHP中处理多维数组时,只需要这样做(我在找类似的做法):
snippets['js'][] = array here
我知道有一两个人提到过如何创建一个多维字典,但我找不到在Python中如何把一个字典添加到另一个字典里的方法。谢谢大家的帮助。
2 个回答
8
来自
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'}]
这样说清楚了吗?
18
这被称为自动生成:
你可以使用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'}]