-
-
Save sdfsdhgjkbmnmxc/38ea79f558012ed08f4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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