读取JSON文件并在Python中按名称排序

zyfwsgd6  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(90)
{
    "customer_data": [
        {
            "name": "John Smith",
            "age": 35,
            "email": "johnsmith@gmail.com",
            "phone": "0413-535-124",
            "sales_value": [
                {
                    "year": "2022",
                    "sales_value": 2000.0
                },
                {
                    "year": "2023",
                    "sales_value": 3000.0
                }
            ]
        },
        {
            "name": "Bob Johnson",
            "age": 30,
            "email": "bjohnson@hotmail.com",
            "phone": "0433-515-912",
            "sales_value": [
                {
                    "year": "2022",
                    "sales_value": 2000.0
                },
                {
                    "year": "2023",
                    "sales_value": 3000.0
                }
            ]
        },
        {
            "name": "Ann Bell",
            "age": 42,
            "email": "ann@hotmail.com",
            "phone": "0433-515-912",
            "sales_value": [
                {
                    "year": "2022",
                    "sales_value": 2000.0
                },
                {
                    "year": "2023",
                    "sales_value": 3000.0
                }
            ]
        },
        {
            "name": "Sony Mart",
            "age": 42,
            "email": "sony@hotmail.com",
            "phone": "0433-515-912",
            "sales_value": [
                {
                    "year": "2022",
                    "sales_value": 5000.0
                },
                {
                    "year": "2023",
                    "sales_value": 3000.0
                }
            ]
        },
        {
            "name": "gg",
            "age": "grgr",
            "email": "gr",
            "phone": "grg",
            "sales_value": [
                {
                    "year": "2022",
                    "sales_value": 454.0
                },
                {
                    "year": "2023",
                    "sales_value": 4545.0
                }
            ]
        }
    ]
}

我需要按名称排序并在Python中重写“customer_data”。请你帮忙。
我试过下面的代码,但没有工作。

def sort_by_key(self, list):
        return list['name']
    def sort_customer_data(self,updated_customer_data):
        #sorted_list = sorted(updated_customer_data['customer_data'], key=lambda x: x['name'])
        #sorted_dict = dict(sorted(updated_customer_data['customer_data'].items(), key=lambda item: item))
        sorted_list = sorted(updated_customer_data,key=self.sort_by_key)
        print(sorted(updated_customer_data, key=self.sort_by_key))
        return output.write_file(appendFile, sorted_list)
rta7y2nd

rta7y2nd1#

这个代码会帮助你

sorted_data = sorted(data["customer_data"], key=lambda x: x["name"])
data["customer_data"] = sorted_data

相关问题