如何从python字典列表中的项中删除字符串的部分和None值?

2023-02-06 15:17:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从python字典列表中删除所有“/api/1/employees/”和/api/1/seats/”。最简单的方法是什么。我的字典列表目前看起来是这样的-dict1 = [{'to_seat_url': '/api/1/seats/19014', 'id': 5051, 'employee_url': '/api/1/employees/4027'}, {'to_seat_url': '/api/1/seats/19013', 'id': 5052, 'employee_url': '/api/1/employees/4048'}, {'to_seat_url': '/api/1/seats/19012', 'id': 5053, 'employee_url': '/api/1/employees/4117'}, {'to_seat_url': None, 'id': 5054, 'employee_url': '/api/1/employees/15027'}]

除以下结果外:

new_dict = [{'to_seat_url': '19014', 'id': 5051, 'employee_url': '4027'}, {'to_seat_url': '19013', 'id': 5052, 'employee_url': '4048'}, {'to_seat_url': '19012', 'id': 5053, 'employee_url': '4117'}, {'to_seat_url': '', 'id': 5054, 'employee_url': '15027'}]


Tags: to方法noneapiidurl列表new字典employeedictseatseatsemployeesdict1
1条回答
网友
1楼 · 发布于 2023-02-06 15:17:13

如果需要URL的最后一部分:

new_dict = [
    {k: v.split("/")[-1] if k != "id" else v for k, v in d.items()}
    for d in dict1
]
print(new_dict)

印刷品:

[
    {"to_seat_url": "19014", "id": 5051, "employee_url": "4027"},
    {"to_seat_url": "19013", "id": 5052, "employee_url": "4048"},
    {"to_seat_url": "19012", "id": 5053, "employee_url": "4117"},
    {"to_seat_url": "9765", "id": 5054, "employee_url": "15027"},
]

编辑:要筛选出None值:

new_dict = [
    {k: v.split("/")[-1] if k != "id" else v for k, v in d.items()}
    for d in dict1
    if not d is None
]
print(new_dict)

编辑2:如果某些值为None

new_dict = [
    {
        k: ("" if v is None else v.split("/")[-1]) if k != "id" else v
        for k, v in d.items()
    }
    for d in dict1
    if not d is None
]
print(new_dict)

相关问题 更多 >