Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #78446

Re: trouble building data structure

From Ned Batchelder <ned@nedbatchelder.com>
Subject Re: trouble building data structure
Date 2014-09-28 20:21 -0400
References <CALDD_=k3Q+fGKw26pQO11OFLSJWkGxXCmBprVv+fjefefNw-uA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.14458.1411950104.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: trouble building data structure Ned Batchelder <ned@nedbatchelder.com> - 2014-09-28 20:21 -0400

csiph-web