3

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?

1
  • 1
    So... sections = {keyword: {}}? Commented Mar 18, 2015 at 20:02

2 Answers 2

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={}) 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.

Sign up to request clarification or add additional context in comments.

Comments

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'

Alternativly you could use a defaultdict which will automatically create the inner dictionary the first time a keyword is accessed

from collections import defaultdict

sections = defaultdict(dict)

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

1 Comment

Or use setdefault on a regular dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.