Python: Using Dictionary get method to return empty list by default returns None instead!

To solve this you should use Python's defaultdict. The first time you use a key that doesn't exist, the argument to the defaultdict constructor is used to create a value (in this case, a list).

http://docs.python.org/library/collections.html#defaultdict-examples

from collections import defaultdict 

d = defaultdict(list)
for i in range( 0, 10 ):
    for j in range( 0, 100 ):
        d[i].append( j )

You can also pass a function as the argument to defaultdict if you want to do anything more elaborate.


It's not dict.get( i, [] ) that's returning None, it's append. You probably want to use dict.setdefault(i, []).append(j) or just use a defaultdict in the first place.

Here's how you would do it:

d = {}
for i in range( 0, 10 ):
    for j in range( 0, 100 ):
        d.setdefault( i, [] ).append( j )

Note that I changed dict to d because dict already means something in Python (you're redefining it) and I removed the superfluous dict[i] = that was causing the error message.


The problem is that append returns None instead of the list object. So

dict[i] = dict.get( i, [] ).append( j ) assigns None to dict[i]

However, you can do much simpler:

dict.setdefault( i, [] ).append( j )

.. quoting the docs for setdefault:

If key is in the dictionary, return its value. If not, insert key with a value of default and return default

So if the key i is not yet present it creates it and stores the default value in it, in either case it returns the key value - which is a reference to the list, so you can modify it directly.