Skip to content

Instantly share code, notes, and snippets.

@theSage21
Created January 28, 2020 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theSage21/406b2b044f7ed0b4dc12312a08e7183b to your computer and use it in GitHub Desktop.
Save theSage21/406b2b044f7ed0b4dc12312a08e7183b to your computer and use it in GitHub Desktop.
d = {
"a1": {
"b1": {
"c1": {4, 5},
"c2": "123",
"c3": tuple(),
"c4": 100_000,
"c5": 1 ** 200000,
},
"b2": "something else",
"b3": 10,
},
"a2": None,
"a3": -1,
}
def flatten(d):
for k, v in d.items():
if isinstance(v, dict):
for other_keys, sub_val in flatten(v):
yield (k, *other_keys), sub_val
else:
yield (k,), v
for k, v in flatten(d):
print(f"{str(k):>30} {v}")
# ('a1', 'b1', 'c1') {4, 5}
# ('a1', 'b1', 'c2') 123
# ('a1', 'b1', 'c3') ()
# ('a1', 'b1', 'c4') 100000
# ('a1', 'b1', 'c5') 1
# ('a1', 'b2') something else
# ('a1', 'b3') 10
# ('a2',) None
# ('a3',) -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment