trouble building data structure

Ned Batchelder ned at nedbatchelder.com
Sun Sep 28 20:21:30 EDT 2014


On 9/28/14 8:04 PM, David Alban wrote:
> i'm writing a program to scan a data file.  from each line of the data
> file i'd like to add something like below to a dictionary.  my perl
> background makes me want python to autovivify, but when i do:
>
>        file_data = {}
>
>        [... as i loop through lines in the file ...]
>
>            file_data[ md5sum ][ inode ] = { 'path' : path, 'size' : size, }
>
> i get:
>
> Traceback (most recent call last):
>    File "foo.py", line 45, in <module>
>      file_data[ md5sum ][ inode ] = { 'path' : path, 'size' : size, }
> KeyError: '91b152ce64af8af91dfe275575a20489'
>
> what is the pythonic way to build my "file_data" data structure above
> that has the above structure?
>

If you want file_data to be a dictionary of dictionaries, use a defaultdict:

     file_data = collections.defaultdict(dict)

This is Python's version of autovivification.  When you access a key 
that doesn't exist, the defaultdict will use the callable you gave it 
(in this case, dict) to create the new value as needed.

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list