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': None, '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': '', '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"},
]
EDIT: To filter-out None
values:
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)
EDIT 2: If some values are 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)