OneCompiler

Merge data by features

263

Grouping the products with the same features

  • e.g. P001 and P003 should be grouped together.
 data = [
  {"productID": "P001", "features": [{"color": "red", "size": "M"}]},
  {"productID": "P002", "features": [{"color": "blue", "size": "M"}]},
  {"productID": "P003", "features": [{"color": "red", "size": "M"}]},
  {"productID": "P004", "features": [{"color": "red", "size": "S"}]},
  {"productID": "P005", "features": [{"color": "yellow", "size": "M"}]},
  {"productID": "P006", "features": [{"color": "blue", "size": "M"}]},
  {"productID": "P007", "features": [{"color": "white", "size": "L"}]},
  {"productID": "P008", "features": [{"color": "yellow", "size": "L"}]},
  {"productID": "P009", "features": [{"color": "yellow", "size": "M"}]},
  {"productID": "P010", "features": [{"color": "white", "size": "L"}]},
  {"productID": "P011", "features": [{"color": "green", "size": "L"}]},
  {"productID": "P012", "features": [{"color": "green", "size": "L"}]}
] 
def merge(_data, reserve_order=False):
  sort = lambda features: sorted(features, key=lambda f: (f['color'], f['size'])) if not reserve_order else features
  key = lambda d: ''.join(map(lambda fe: f"{fe['color']}{fe['size']}", sort(d['features'])))
  result = {}
  for d in _data:
    k = key(d)
    if not result.get(k): result[k] = []
    result[k].append(d)
  return list(result.values())