Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get Python to automatically create missing key/value pairs in a dictionary? [duplicate]

Tags:

python

I'm creating a dictionary structure that is several levels deep. I'm trying to do something like the following:

dict = {}
dict['a']['b'] = True

At the moment the above fails because key 'a' does not exist. At the moment I have to check at every level of nesting and manually insert an empty dictionary. Is there some type of syntactic sugar to be able to do something like the above can produce:

{'a': {'b': True}}

Without having to create an empty dictionary at each level of nesting?

like image 322
deltanovember Avatar asked May 23 '13 22:05

deltanovember


2 Answers

As others have said, use defaultdict. This is the idiom I prefer for arbitrarily-deep nesting of dictionaries:

def nested_dict():
    return collections.defaultdict(nested_dict)

d = nested_dict()
d[1][2][3] = 'Hello, dictionary!'
print(d[1][2][3]) # Prints Hello, dictionary!

This also makes checking whether an element exists a little nicer, too, since you may no longer need to use get:

if not d[2][3][4][5]:
    print('That element is empty!')

This has been edited to use a def rather than a lambda for pep8 compliance. The original lambda form looked like this below, which has the drawback of being called <lambda> everywhere instead of getting a proper function name.

>>> nested_dict = lambda: collections.defaultdict(nested_dict)
>>> d = nested_dict()
>>> d[1][2][3]
defaultdict(<function <lambda> at 0x037E7540>, {})
like image 110
Henry Keiter Avatar answered Sep 24 '22 00:09

Henry Keiter


Use defaultdict.

Python: defaultdict of defaultdict?

like image 23
Matt Ball Avatar answered Sep 24 '22 00:09

Matt Ball