python列表自定义json格式

时间:2017-10-05 08:07:48

标签: python json

我在python中有以下列表:

response = [{u'Owner Name': u'Ashish Bainade', u'Unit ID': u'102', u'Wing': 
u'B'}, {u'Owner Name': u'Sagar Dhondhe', u'Unit ID': u'104', u'Wing': u'B'}, 
{u'Owner Name': u'Akshara Bainade', u'Unit ID': u'105', u'Wing': u'D'}]

我必须以下面的json格式发送回复:

Wings : [ { "wing name" :"B",Flat : [{"Unit ID" : 102 , "owner name" : 
"Ashish Bainade"},{"Unit ID" : 104 , "owner name" : "Sagar Dhondhe"} ] },
  { "wing name" :"D",Flat : [{"Unit ID" : 105 , "owner name" : "Akshara 
Bainade"}] 
}]           

1 个答案:

答案 0 :(得分:2)

您可以使用itertools.groupby使用'Wing'字段对dicts进行分组,然后构建新的数据结构,从每个嵌套字典中排除该字段:

from itertools import groupby

group_by_field = 'Wing'
f = lambda x: x[group_by_field]  

result = [{'Wing name': k, 
           'Flat': [{k: d[k] for k in set(d)-{group_by_field,}} for d in g]} 
                             for k, g in groupby(sorted(response, key=f), f)]
print(result)
[{'Flat': [{'Owner Name': 'Ashish Bainade', 'Unit ID': '102'},
           {'Owner Name': 'Sagar Dhondhe', 'Unit ID': '104'}],
  'Wing name': 'B'},
 {'Flat': [{'Owner Name': 'Akshara Bainade', 'Unit ID': '105'}],
  'Wing name': 'D'}]

使用itertools.groupby需要预先分类。