I want to define a nested dictionary in python. I tried the following:
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'
I can do this:
sections = {}
sections[keyword] = {}
But then there is a warning in the Pycharm saying it can be defined through dictionary label.
Can someone point out how to achieve this?
解决方案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={}) creates a dict with the string "keyword" as the key not the value of the variable keyword.
In [3]: dict(foo={})
Out[3]: {'foo': {}}
Where using a dict literal actually uses the value of the variable as above.