Created
January 28, 2020 11:00
-
-
Save theSage21/406b2b044f7ed0b4dc12312a08e7183b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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