Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #78445
| References | <CALDD_=k3Q+fGKw26pQO11OFLSJWkGxXCmBprVv+fjefefNw-uA@mail.gmail.com> |
|---|---|
| Date | 2014-09-29 10:20 +1000 |
| Subject | Re: trouble building data structure |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.14457.1411950022.18130.python-list@python.org> (permalink) |
On Mon, Sep 29, 2014 at 10:04 AM, David Alban <extasia@extasia.org> wrote:
> file_data = {}
>
> [... as i loop through lines in the file ...]
>
> file_data[ md5sum ][ inode ] = { 'path' : path, 'size' : size, }
>
> what is the pythonic way to build my "file_data" data structure above that
> has the above structure?
The easiest way would be with a defaultdict. It's a subclass of
dictionary that does what you're looking for. You'd use it something
like this:
from collections import defaultdict
file_data = defaultdict(dict)
# then continue with the program as normal
# including the loop and assignments that you have above
Any time it's asked to look up an MD5 that doesn't exist yet, it'll
create a new dictionary by calling dict(), and that sets up the next
level for you.
Docs are here:
https://docs.python.org/2/library/collections.html#collections.defaultdict
https://docs.python.org/3/library/collections.html#collections.defaultdict
You can also use the setdefault() method of the regular dictionary,
which makes sense if you have just a few places where you need this
behaviour.
ChrisA
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: trouble building data structure Chris Angelico <rosuav@gmail.com> - 2014-09-29 10:20 +1000
csiph-web