在python中定义嵌套字典

时间:2015-03-18 19:59:26

标签: python dictionary

我想在python中定义一个嵌套字典。我尝试了以下方法:

keyword = 'MyTest' # Later I want to pull this iterating through a list
key = 'test1'
sections = dict(keyword={}) #This is clearly wrong but how do I get the string representation?
sections[keyword][key] = 'Some value'

我可以这样做:

sections = {}
sections[keyword] = {}

然后在Pycharm中有一个警告说它可以通过字典标签来定义。

有人可以指出如何实现这个目标吗?

2 个答案:

答案 0 :(得分:5)

keyword = 'MyTest' # Later I want to pull this iterating through a list
key = 'test1'
sections = {keyword: {}} 
sections[keyword][key] = 'Some value'

print(sections)
{'MyTest': {'test1': 'Some value'}}

dict(keyword={})创建一个字符串为"keyword"的字典,而不是变量关键字的值。

In [3]: dict(foo={})
Out[3]: {'foo': {}}

使用dict文字实际上使用上面变量的值。

答案 1 :(得分:0)

sections = {}

keyword = 'MyTest'
# If keyword isn't yet a key in the sections dict, 
# add it and set the value to an empty dict
if keyword not in sections:
    sections[keyword] = {} 

key = 'test1'
sections[keyword][key] = 'Some value'

另外,你可以使用defaultdict,它会在第一次访问关键字时自动创建内部字典

from collections import defaultdict

sections = defaultdict(dict)

keyword = 'MyTest'
key = 'test1'
sections[keyword][key] = 'Some value'