Skip to content

Instantly share code, notes, and snippets.

@HotcockMiami
Created November 5, 2020 13:11
Show Gist options
  • Save HotcockMiami/3d155220796df87e40cfade4c6e236a7 to your computer and use it in GitHub Desktop.
Save HotcockMiami/3d155220796df87e40cfade4c6e236a7 to your computer and use it in GitHub Desktop.
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