Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #78445 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2014-09-29 10:20 +1000 |
| Last post | 2014-09-29 10:20 +1000 |
| 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.
Re: trouble building data structure Chris Angelico <rosuav@gmail.com> - 2014-09-29 10:20 +1000
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-09-29 10:20 +1000 |
| Subject | Re: trouble building data structure |
| Message-ID | <mailman.14457.1411950022.18130.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web