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


Groups > comp.lang.python > #78446 > unrolled thread

Re: trouble building data structure

Started byNed Batchelder <ned@nedbatchelder.com>
First post2014-09-28 20:21 -0400
Last post2014-09-28 20:21 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#78446 — Re: trouble building data structure

FromNed Batchelder <ned@nedbatchelder.com>
Date2014-09-28 20:21 -0400
SubjectRe: trouble building data structure
Message-ID<mailman.14458.1411950104.18130.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web