Skip to content

Instantly share code, notes, and snippets.

@sdfsdhgjkbmnmxc
Forked from anonymous/flatten
Last active August 29, 2015 14:03
Show Gist options
  • Save sdfsdhgjkbmnmxc/38ea79f558012ed08f4b to your computer and use it in GitHub Desktop.
Save sdfsdhgjkbmnmxc/38ea79f558012ed08f4b to your computer and use it in GitHub Desktop.
def flatten(dictionary):
"""
>>> flatten({})
{}
>>> flatten({
... "name": {
... "first": "One",
... "last": "Drone",
... },
... "job": "scout",
... "recent": {},
... "additional": {
... "place": {
... "zone": "1",
... "cell": "2",
... },
... },
... })
{'additional/place/zone': '1', 'job': 'scout', 'additional/place/cell': '2', 'name/first': 'One', 'name/last': 'Drone'}
>>> flatten({"empty": {}})
{'empty': ''}
"""
stack = [
((), dictionary),
]
result = {}
while stack:
path, current = stack.pop()
for k, v in current.items():
new_k = path + (k,)
if isinstance(v, dict):
stack.append((new_k, v))
else:
result['/'.join(new_k)] = v
return result
if __name__ == '__main__':
import doctest
doctest.testmod()
print 'tests passed'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment