Skip to content

Instantly share code, notes, and snippets.

@theSage21
Created Jan 28, 2020
Embed
What would you like to do?
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