Home > Enterprise >  How can I remove special characters from list of dictionaries in python
How can I remove special characters from list of dictionaries in python

Time:09-24

I am trying to remove all the '/api/1/employees/' and /api/1/seats/ from the python list of dictionaries. What is the easiest way to do so. My list of dictionaries are looking like this at the moment -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': '/api/1/seats/9765', 'id': 5054, 'employee_url': '/api/1/employees/15027'}]

excepting below result:

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'}]

CodePudding user response:

If you want last part of the URLs:

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

Prints:

[
    {"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"},
]
  • Related