Python代码实现扁平化字典
以下是实现扁平化字典的一段代码,in_data是输入数据,out_data是输出数据。
1 in_data= { 2 u'deliveryOrder': { 3 u'warehouseCode': u'OTHER', 4 u'deliveryOrderCode': u'3600120100000', 5 u'receiverInfo': { 6 u'detailAddress': u'\u5927\u5382\u680818\u53f7101', 7 u'city': u'\u4e94\u8fde', 8 u'province': u'\u5c71\u4e1c', 9 u'area': u'\u5927\u5382' 10 }, 11 u'senderInfo': { 12 u'detailAddress': u'\u6587\u4e09\u8def172\u53f7', 13 u'city': u'\u676d\u5dde', 14 }, 15 }, 16 u'orderLines': { 17 u'orderLine': { 18 u'itemId': u'0192010101', 19 u'planQty': u'20', 20 } 21 } 22 } 23 24 #定义key的转换规则 25 match_list = {'area': 'receiver_area', 'city': 'receiver_city', 'deliveryOrderCode': 'express_code','detailAddress': 'receiver_address','province': 'receiver_province','warehouseCode': 'warehouse_code'} 26 27 #初始化out_data 28 out_data={} 29 30 31 def trans(in_data, match_list): 32 #在新建的out_data中写入key和value 33 for k,v in in_data.items(): 34 if (isinstance(v, dict)): 35 if k == 'orderLines': 36 out_data['lines']= [{'item_id':v['orderLine']['itemId'], 'product_qty':v['orderLine']['planQty']}] 37 elif k == 'senderInfo': 38 out_data['sender_city'] = v['city'] 39 out_data['sender_address'] = v['detailAddress'] 40 else: 41 trans(v, match_list) 42 else: 43 out_data[k] = v 44 45 #将out_data的key变换成目标key 46 for k,v in out_data.items(): 47 if k in match_list.keys(): 48 out_data[match_list[k]] = v 49 del out_data[k] 50 51 #返回out_data 52 print("in_data:{}".format(in_data)) 53 print("out_data:{}\n".format(out_data))54 return out_data 55 trans(in_data, match_list)
以下是在mac os python 3.5环境执行代码的结果。
1 in_data:{'detailAddress': '大厂栈18号101', 'city': '五连', 'province': '山东', 'area': '大厂'} 2 out_data:{'receiver_address': '大厂栈18号101', 'receiver_area': '大厂', 'receiver_province': '山东', 'sender_city': '杭州', 'receiver_city': '五连', 'sender_address': '文三路172号'} 3 4 in_data:{'senderInfo': {'detailAddress': '文三路172号', 'city': '杭州'}, 'receiverInfo': {'detailAddress': '大厂栈18号101', 'city': '五连', 'province': '山东', 'area': '大厂'}, 'deliveryOrderCode': '3600120100000', 'warehouseCode': 'OTHER'} 5 out_data:{'receiver_address': '大厂栈18号101', 'warehouse_code': 'OTHER', 'receiver_area': '大厂', 'receiver_province': '山东', 'express_code': '3600120100000', 'sender_city': '杭州', 'receiver_city': '五连', 'sender_address': '文三路172号'} 6 7 in_data:{'deliveryOrder': {'senderInfo': {'detailAddress': '文三路172号', 'city': '杭州'}, 'receiverInfo': {'detailAddress': '大厂栈18号101', 'city': '五连', 'province': '山东', 'area': '大厂'}, 'deliveryOrderCode': '3600120100000', 'warehouseCode': 'OTHER'}, 'orderLines': {'orderLine': {'planQty': '20', 'itemId': '0192010101'}}} 8 out_data:{'receiver_address': '大厂栈18号101', 'warehouse_code': 'OTHER', 'receiver_area': '大厂', 'receiver_province': '山东', 'express_code': '3600120100000', 'sender_city': '杭州', 'lines': [{'product_qty': '20', 'item_id': '0192010101'}], 'receiver_city': '五连', 'sender_address': '文三路172号'}