Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. def copy_condensed(obj, index:int = 0):
  2. """Copies an object recursively while dropping all but one element of lists.
  3.  
  4. Typically for objects converted from JSON data, for basic visualization of contents.
  5.  
  6. Example usage:
  7.  
  8. >>> import json
  9. >>> with open('foo.json') as f:
  10. ... data_dict = json.load(f)
  11. ...
  12. >>> compact_dict = copy_condensed(data_dict, -1)
  13. >>> print(json.dumps(compact_dict, indent=2))
  14. {
  15. "activity": [
  16. "136 items",
  17. {
  18. "average_met": 1.09375,
  19. "cal_active": 4,
  20. "cal_total": 1957
  21. }
  22. ],
  23. "sleep": [
  24. "124 items",
  25. {
  26. "awake": 720,
  27. "deep": 7860,
  28. "duration": 21900,
  29. "efficiency": 97,
  30. "hr_5min": [
  31. "74 items",
  32. 46
  33. ]
  34. }
  35. ]
  36. }
  37.  
  38. :param obj: Object to be condensed
  39. :type obj: dict, list, int, float, str
  40. :param index: Index of list element to be kept
  41. :type index: int
  42. :returns Condensed object
  43. """
  44. if type(obj) is list:
  45. return [f"{len(obj)} items", copy_condensed(obj[index], index)]
  46. elif type(obj) is dict:
  47. return {k: copy_condensed(v, index) for k,v in obj.items()}
  48. else:
  49. assert type(obj) in [int, float, str]
  50. return obj
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement