Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def copy_condensed(obj, index:int = 0):
- """Copies an object recursively while dropping all but one element of lists.
- Typically for objects converted from JSON data, for basic visualization of contents.
- Example usage:
- >>> import json
- >>> with open('foo.json') as f:
- ... data_dict = json.load(f)
- ...
- >>> compact_dict = copy_condensed(data_dict, -1)
- >>> print(json.dumps(compact_dict, indent=2))
- {
- "activity": [
- "136 items",
- {
- "average_met": 1.09375,
- "cal_active": 4,
- "cal_total": 1957
- }
- ],
- "sleep": [
- "124 items",
- {
- "awake": 720,
- "deep": 7860,
- "duration": 21900,
- "efficiency": 97,
- "hr_5min": [
- "74 items",
- 46
- ]
- }
- ]
- }
- :param obj: Object to be condensed
- :type obj: dict, list, int, float, str
- :param index: Index of list element to be kept
- :type index: int
- :returns Condensed object
- """
- if type(obj) is list:
- return [f"{len(obj)} items", copy_condensed(obj[index], index)]
- elif type(obj) is dict:
- return {k: copy_condensed(v, index) for k,v in obj.items()}
- else:
- assert type(obj) in [int, float, str]
- return obj
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement