David Alban wrote: > greetings, > > 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?
Others have suggested using a defaultdict, but here's an older solution: use the setdefault method on regular dicts. This fails: py> file_data = {} py> file_data[1234][23] = {'spam': 1, 'eggs': 2} Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 1234 But this succeeds: py> file_data.setdefault(1234, {})[23] = {'spam': 1, 'eggs': 2} py> file_data.setdefault(5678, {})[42] = {'spam': 3, 'cheese': 1} py> file_data {1234: {23: {'spam': 1, 'eggs': 2}}, 5678: {42: {'spam': 3, 'cheese': 1}}} Whether you prefer to use setdefault, or a defaultdict, is a matter of taste. -- Steven -- https://mail.python.org/mailman/listinfo/python-list