用Python更新和创建多维字典

2024-06-01 02:00:01 发布

您现在位置: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中找到如何将字典添加到字典的方法。谢谢你的帮助。


Tags: 代码text语言信息idjson字典here
2条回答

这叫做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的思想是在访问键时自动创建元素。顺便说一下,对于这个简单的例子,您可以简单地执行以下操作:

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

明白了吗?

相关问题 更多 >