Dictionary with Lists

Mel mwilson at the-wire.com
Sun Oct 4 00:44:26 CEST 2009


Shaun wrote:
> testDict = {}
> ...
> testDict [1] = testDict.get (1, []).append ("Test0")  # 1 does not
> exist, create empty array
> print testDict
> testDict [1] = testDict.get (1, []).append ("Test1")
> print testDict
> 
[ ... ]
> However, the first printout gives {1: None}  instead of the desired
> {1: ['test']}.  What's wrong with this syntax?

The trouble is that the list.append method returns None, after modifying the 
value of the parent list in place.  So of course, None gets assigned to 
testDict[1] after the valuable work has been done.

The old way to do what you want is

testDict.setdefault (1, []).append ("Test0")

The new way is to inherit from defaultdict.

	Mel.





More information about the Python-list mailing list