fork download
  1. from itertools import groupby
  2. import pprint
  3.  
  4. pp=pprint.PrettyPrinter()
  5.  
  6. data = [{'location': 'eastus', 'sku': 'S', 'term': 'P1', 'scope': '1'},
  7. {'location': 'india', 'sku': 'a', 'term': 'P1', 'scope': '2'},
  8. {'location': 'eastus', 'sku': 'S', 'term': 'P3', 'scope': '3'},
  9. {'location': 'india', 'sku': 'f', 'term': 'P1', 'scope': '4'},
  10. {'location': 'japan', 'sku': 'a', 'term': 'P1', 'scope': '5'},
  11. {'location': 'india', 'sku': 'a', 'term': 'P3', 'scope': '6'}]
  12.  
  13. pp.pprint([(lambda k,g:k.update({"new_key":[(lambda i:i.pop("location") and i.pop("sku") and i)(item) for item in g]}) or k)(k,g) for k,g in groupby(sorted(data,key=lambda i:(i["location"],i["sku"])), lambda i:{"location":i["location"],"sku":i["sku"]})])
  14.  
Success #stdin #stdout 0.02s 27968KB
stdin
Standard input is empty
stdout
[{'location': 'eastus',
  'new_key': [{'scope': '1', 'term': 'P1'}, {'scope': '3', 'term': 'P3'}],
  'sku': 'S'},
 {'location': 'india',
  'new_key': [{'scope': '2', 'term': 'P1'}, {'scope': '6', 'term': 'P3'}],
  'sku': 'a'},
 {'location': 'india', 'new_key': [{'scope': '4', 'term': 'P1'}], 'sku': 'f'},
 {'location': 'japan', 'new_key': [{'scope': '5', 'term': 'P1'}], 'sku': 'a'}]