SHARE
TWEET

Untitled

a guest Sep 16th, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def flatten(nested, column_names):
  2.     all_dicts = []
  3.     final_result = {}
  4.     index = 0
  5.  
  6.     def recurse(data):
  7.         for k, v in data.items():
  8.             final_result = {}
  9.             if isinstance(v, dict):
  10.                 if any(isinstance(i,dict) for i in v.values()):
  11.                     recurse(v)
  12.                 else:
  13.                     final_result.update(v)
  14.                     all_dicts.append(final_result.copy())
  15.             else:
  16.                 final_result[k]=v
  17.                 all_dicts.append(final_result.copy())
  18.  
  19.     recurse(nested)
  20.     return all_dicts
  21.  
  22.  
  23.  
  24. def flatten2(nested, column_names):
  25.     all_dicts = []
  26.     final_result = {}
  27.     index = 0
  28.  
  29.     def recurse(data, existing = []):
  30.         for k, v in data.items():
  31.             final_result = {}
  32.             if isinstance(v, dict):
  33.                 if any(isinstance(i,dict) for i in v.values()):
  34.                     existing.append(k)
  35.                     recurse(v, existing=existing)
  36.                 else:
  37.                     final_result.update(v)
  38.                     final_result.update(zip(column_names[:len(existing)], existing))
  39.                     all_dicts.append(final_result.copy())
  40.             else:
  41.                 final_result[k]=v
  42.                 final_result.update(zip(column_names[:len(existing)], existing))
  43.                 all_dicts.append(final_result.copy())
  44.  
  45.     recurse(nested)
  46.     return all_dicts
  47.  
  48.  
  49. a = {
  50.     'foo': {
  51.         'cat': {'name': 'Hodor',  'age': 7},
  52.         'dog': {'name': 'Mordor', 'age': 5},
  53.     },
  54.     'bar': {
  55.         'rat': {'name': 'Izidor', 'age': 3},
  56.         'ratv': {'nameb': 'Izidor', 'age': 3},
  57.     },
  58.     'baz': 'woops',
  59. }
  60. print(flatten(a, ['foobar', 'animal']))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top