Wednesday, 3 February 2016

Python - Initialising nested dictionaries

This is something I will never remember ...

In Python, if you're using a nested dictionary you need initialise the first dictionary before you can assign the second. If you think about it it makes sense, but if you're just writing code ... not so much.

You might be tempted to write:

myDict[someDict][0] = blah

as obviously that's a perfectly acceptable way of doing things. Sadly, that will throw a TypeError because myDict[someDict] is actually None. You haven't initialised it.

So what you need to do is:

myDict[someDict] = {}
myDict[someDict][0] = blah

As always, thank you to stackoverflow for fleshing out the deficiencies in Python's doco.

Labels: , ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home