Skip to content

Instantly share code, notes, and snippets.

@sprin
Created November 8, 2013 02:42
Show Gist options
  • Save sprin/7365454 to your computer and use it in GitHub Desktop.
Save sprin/7365454 to your computer and use it in GitHub Desktop.
Unroll a nested dictionary into flat lists.
"""
Unroll a nested dictionary into flat lists.
This might come in handy if you have on your hands a massive, hardcoded,
vertical- and horizontal-screen-spanning lookup map, and you would like to get
it into a tabular format, so you can, for example, load it into a relational
database table.
"""
import sys
import csv
# Example
d = {'a':
{'c':
{'e': 1,
'f': 2},
'd':
{'e': 3,
'f': 4},
},
'b':
{'c':
{'e': 5,
'f': 6},
'd':
{'e': 7,
'f': 8},
}
}
def unroll_dict(dict_):
ret = []
for k, v in dict_.iteritems():
# Recursive case, value is another dict
if isinstance(v, dict):
unrolled = unroll_dict(v)
for u in unrolled:
ret.append([k] + u)
# Base case, value is not dict
else:
ret.append([k, v])
return ret
unrolled = unroll_dict(d)
writer = csv.writer(sys.stdout, delimiter='\t')
for row in unrolled:
writer.writerow(row)
# Prints:
"""
a c e 1
a c f 2
a d e 3
a d f 4
b c e 5
b c f 6
b d e 7
b d f 8
"""
@sprin
Copy link
Author

sprin commented Nov 8, 2013

MIT LICENSE

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment