sample_data = {
'person:name': 'Guido',
'person:fullname': 'Guido van Rossum',
'person:department:title': 'Python developers',
'person:department:post:title': 'chief',
'person:department:post:since': '2013-01-01',
'person:department:post:till': 'now',
'address:country': 'Nederland, USA',
'family status': 'married'
}
expected_results = {
'address': {
'country': 'Nederland, USA'
},
'family status': 'married',
'person': {
'name': 'Guido',
'fullname': 'Guido van Rossum',
'department': {
'title': 'Python developers',
'post': {
'since': '2013-01-01',
'till': 'now',
'title': 'chief'
}
}
}
}
def unflatten(dictionary):
resultDict = dict()
for key, value in dictionary.items():
parts = key.split(":")
d = resultDict
for part in parts[:-1]:
if part not in d:
d[part] = dict()
d = d[part]
d[parts[-1]] = value
return resultDict
r = unflatten(sample_data)
print(r)
print(r==expected_results)
c2FtcGxlX2RhdGEgPSB7CiAgJ3BlcnNvbjpuYW1lJzogJ0d1aWRvJywKICAncGVyc29uOmZ1bGxuYW1lJzogJ0d1aWRvIHZhbiBSb3NzdW0nLAogICdwZXJzb246ZGVwYXJ0bWVudDp0aXRsZSc6ICdQeXRob24gZGV2ZWxvcGVycycsCiAgJ3BlcnNvbjpkZXBhcnRtZW50OnBvc3Q6dGl0bGUnOiAnY2hpZWYnLAogICdwZXJzb246ZGVwYXJ0bWVudDpwb3N0OnNpbmNlJzogJzIwMTMtMDEtMDEnLAogICdwZXJzb246ZGVwYXJ0bWVudDpwb3N0OnRpbGwnOiAnbm93JywKICAnYWRkcmVzczpjb3VudHJ5JzogJ05lZGVybGFuZCwgVVNBJywKICAnZmFtaWx5IHN0YXR1cyc6ICdtYXJyaWVkJwp9CgoKZXhwZWN0ZWRfcmVzdWx0cyA9IHsKICAnYWRkcmVzcyc6IHsKICAgICdjb3VudHJ5JzogJ05lZGVybGFuZCwgVVNBJwogIH0sCiAgJ2ZhbWlseSBzdGF0dXMnOiAnbWFycmllZCcsCiAgJ3BlcnNvbic6IHsKICAgICduYW1lJzogJ0d1aWRvJywKICAgICdmdWxsbmFtZSc6ICdHdWlkbyB2YW4gUm9zc3VtJywKICAgICdkZXBhcnRtZW50JzogewogICAgICAndGl0bGUnOiAnUHl0aG9uIGRldmVsb3BlcnMnLAogICAgICAncG9zdCc6IHsKICAgICAgICAnc2luY2UnOiAnMjAxMy0wMS0wMScsCiAgICAgICAgJ3RpbGwnOiAnbm93JywKICAgICAgICAndGl0bGUnOiAnY2hpZWYnCiAgICAgIH0KICAgIH0KICB9Cn0KCmRlZiB1bmZsYXR0ZW4oZGljdGlvbmFyeSk6CiAgICByZXN1bHREaWN0ID0gZGljdCgpCiAgICBmb3Iga2V5LCB2YWx1ZSBpbiBkaWN0aW9uYXJ5Lml0ZW1zKCk6CiAgICAgICAgcGFydHMgPSBrZXkuc3BsaXQoIjoiKQogICAgICAgIGQgPSByZXN1bHREaWN0CiAgICAgICAgZm9yIHBhcnQgaW4gcGFydHNbOi0xXToKICAgICAgICAgICAgaWYgcGFydCBub3QgaW4gZDoKICAgICAgICAgICAgICAgIGRbcGFydF0gPSBkaWN0KCkKICAgICAgICAgICAgZCA9IGRbcGFydF0KICAgICAgICBkW3BhcnRzWy0xXV0gPSB2YWx1ZQogICAgcmV0dXJuIHJlc3VsdERpY3QKCgpyID0gdW5mbGF0dGVuKHNhbXBsZV9kYXRhKQoKcHJpbnQocikKcHJpbnQocj09ZXhwZWN0ZWRfcmVzdWx0cyk=
{'person': {'name': 'Guido', 'department': {'post': {'since': '2013-01-01', 'title': 'chief', 'till': 'now'}, 'title': 'Python developers'}, 'fullname': 'Guido van Rossum'}, 'family status': 'married', 'address': {'country': 'Nederland, USA'}}
True