as3rdaccount
as3rdaccount

Reputation: 3951

Defining a nested dictionary in python

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?

Upvotes: 3

Views: 929

Answers (2)

user1672292
user1672292

Reputation: 51

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'

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180540

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.

Upvotes: 5

Related Questions