Try95th

simplifyObj

Nov 16th, 2022 (edited)
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. ### simplify nested dictionaries [or stringify and truncate] ###
  2. ####### sample usage at  https://pastebin.com/LcqTjYNZ #########
  3.  
  4. def simplifyObj(mList, kKey=None, cKey=None, sKey=None, maxLen=50):
  5.     if maxLen is not None and (type(maxLen) != int or maxLen < 15):
  6.         maxLen = 50
  7.     if kKey is None or (cKey is None and sKey is None):
  8.         if type(mList) in [bool, int, float]: return mList
  9.         if type(mList) in [tuple, list]:
  10.             simplified = [simplifyObj(m, maxLen=maxLen) for m in mList]
  11.             return tuple(simplified) if type(mList) == tuple else simplified
  12.         if type(mList) == dict:
  13.             return {k: simplifyObj(v, maxLen=maxLen) for k, v in mList.items()}
  14.  
  15.     if type(mList) != list:
  16.         # stringify and truncate
  17.         mList = str(mList)
  18.         if maxLen is not None and len(mList) > maxLen:
  19.             mList = mList[:maxLen-7] + '...' + mList[-8:]
  20.         return mList
  21.     return {
  22.         str(d[kKey]): simplifyObj(
  23.             d[cKey] if cKey in d else d[sKey], kKey, cKey, sKey, maxLen
  24.         ) for d in mList if type(d) == dict and kKey in d and ((
  25.             sKey is not None and sKey in d and type(d[sKey] == list
  26.         )) or (cKey is not None and cKey in d))
  27.     }
Advertisement
Add Comment
Please, Sign In to add comment