fork(2) download
  1. sample_data = {
  2. 'person:name': 'Guido',
  3. 'person:fullname': 'Guido van Rossum',
  4. 'person:department:title': 'Python developers',
  5. 'person:department:post:title': 'chief',
  6. 'person:department:post:since': '2013-01-01',
  7. 'person:department:post:till': 'now',
  8. 'address:country': 'Nederland, USA',
  9. 'family status': 'married'
  10. }
  11.  
  12.  
  13. expected_results = {
  14. 'address': {
  15. 'country': 'Nederland, USA'
  16. },
  17. 'family status': 'married',
  18. 'person': {
  19. 'name': 'Guido',
  20. 'fullname': 'Guido van Rossum',
  21. 'department': {
  22. 'title': 'Python developers',
  23. 'post': {
  24. 'since': '2013-01-01',
  25. 'till': 'now',
  26. 'title': 'chief'
  27. }
  28. }
  29. }
  30. }
  31.  
  32. def unflatten(dictionary):
  33. resultDict = dict()
  34. for key, value in dictionary.items():
  35. parts = key.split(":")
  36. d = resultDict
  37. for part in parts[:-1]:
  38. if part not in d:
  39. d[part] = dict()
  40. d = d[part]
  41. d[parts[-1]] = value
  42. return resultDict
  43.  
  44.  
  45. r = unflatten(sample_data)
  46.  
  47. print(r)
  48. print(r==expected_results)
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
{'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