Python递归练习
调用外部api接口需要排序好的字典形式的字符串,字典默认是带有空格的,所以需要处理,这里运用了递归的思想
主要运用到的几个关键:
1.字典是无序的
2.list是可以排序的
3.字典可以转换为tuple
# coding: utf-8
test = {
"address1":"1 Stafford Crt.",
"address2":"aaaaaaa",
"city":"Bayswater North",
"doorplateNumbers":"109",
"emailAddress":"abc@winit.com",
"phoneNum":"15900001111",
"packageList":[
{
"packageNo":"",
"warehouseCode":"US0003",
"deliveryWayCode":"OSF1010520",
"authBarcode":"",
"eBayOrderID":"3434245-24377766",
"productList":[
{
"eBayBuyerID":"98877456rere",
"eBaySellerID":"99887rtrtr66123",
"eBayItemID":"3434245",
"eBayTransactionID":"24377766",
"productCode":"LCD-IP4-06",
"productNum":"3",
},
{
"eBayBuyerID":"98877456rere",
"eBaySellerID":"99887rtrtr66123",
"eBayItemID":"3434245",
"eBayTransactionID":"24377766",
"productCode":"WLCD-IP4-01",
"productNum":"1",
}
]
}
],
"recipientName":"mingbao",
"region":"WV",
"repeatable":"Y",
"isAuto":"N",
"sellerOrderNo":"PowerSellerABC123",
"state":"US",
"zipCode":"25085"
}
def uuu(key,values):
"""
return string
:param key:
:param values:
:return:
"""
return '"' + key + '":"' + values + '",'
def dd(directions):
"""
排序
:param directions:
:return:
"""
temp = []
for key in directions:
temp.append(key)
temp = sorted(temp)
return temp
def ee(test):
"""
递归
:param test:
:return:
"""
result = '{'
if test==None:
return result
if isinstance(test,dict):
#sorted
sorted_list = dd(test)
print sorted_list
for sorted_item in sorted_list:
result +=ee((sorted_item,test[sorted_item]))
#出口
if isinstance(test,tuple):
#list则另外处理
if isinstance(test[1],list):
s = ''
for t in test[1]:
s += ee(t)+','
s = s[:-1]
return '"'+test[0]+'":['+s+'],'
return uuu(test[0],test[1])
result = result[:-1] +'}'
return result
print ee(test)
打印结果:
{"address1":"1 Stafford Crt.","address2":"aaaaaaa","city":"Bayswater North","doorplateNumbers":"109","emailAddress":"abc@winit.com","isAuto":"N","packageList":[{"authBarcode":"","deliveryWayCode":"OSF1010520","eBayOrderID":"3434245-24377766","packageNo":"","productList":[{"eBayBuyerID":"98877456rere","eBayItemID":"3434245","eBaySellerID":"99887rtrtr66123","eBayTransactionID":"24377766","productCode":"LCD-IP4-06","productNum":"3"},{"eBayBuyerID":"98877456rere","eBayItemID":"3434245","eBaySellerID":"99887rtrtr66123","eBayTransactionID":"24377766","productCode":"WLCD-IP4-01","productNum":"1"}],"warehouseCode":"US0003"}],"phoneNum":"15900001111","recipientName":"mingbao","region":"WV","repeatable":"Y","sellerOrderNo":"PowerSellerABC123","state":"US","zipCode":"25085"}