Created
November 5, 2020 13:11
-
-
Save HotcockMiami/3d155220796df87e40cfade4c6e236a7 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
import unittest | |
d = { | |
"a": 5, | |
"b": 6, | |
"c": { | |
"f": 9, | |
"g": { | |
"m": 17, | |
"n": 3 | |
} | |
} | |
} | |
test_res = { | |
'a': 5, | |
'b': 6, | |
'c.f': 9, | |
'c.g.m': 17, | |
'c.g.n': 3 | |
} | |
def flatten(d): | |
def items(): | |
for key, value in d.items(): # Итерируем по словарю | |
if isinstance(value, dict): # Если элемент - словарь, то итерируем по подуровню | |
for subkey, subvalue in flatten(value).items(): #Итерируем по подсловарю | |
yield key + "." + subkey, subvalue | |
else: | |
yield key, value | |
return dict(items()) | |
class FlattenTests(unittest.TestCase): # Проводим тест | |
def test_equal(self): | |
self.assertEqual(flatten(d), test_res) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment