I am trying to remove all the '/api/1/employees/' and /api/1/seats/ from the python dictionary. What is the easiest way to do so. My dictionary is looking like this at the moment -
dict1 = {5051: ['/api/1/employees/4027', '5051', '/api/1/seats/19014'], 5052: ['/api/1/employees/4048', '5052', '/api/1/seats/19013'], 5053: ['/api/1/employees/4117', '5053', '/api/1/seats/19012'], 5054: ['/api/1/employees/15027', '5054', '/api/1/seats/9765']}
I am expecting below dict
dict1 = {5051: ['4027', '5051', '19014'], 5052: ['4048', '5052', '19013'], 5053: ['4117', '5053', '19012'], 5054: ['15027', '5054', '9765']}
CodePudding user response:
Use str.rsplit
:
dict1 = {k: [s.rsplit("/", 1)[-1] for s in v] for k, v in dict1.items()}
CodePudding user response:
The below works. The idea is to try to convert the entry to int
and if we fail - split the entry and return last element
data = {5051: ['/api/1/employees/4027', '5051', '/api/1/seats/19014'],
5052: ['/api/1/employees/4048', '5052', '/api/1/seats/19013'],
5053: ['/api/1/employees/4117', '5053', '/api/1/seats/19012'],
5054: ['/api/1/employees/15027', '5054', '/api/1/seats/9765']}
def get_int(value):
try:
x = int(value)
return value
except ValueError:
return value.split('/')[-1]
data = {k: [get_int(vv) for vv in v] for k,v in data.items()}
print(data)
output
{5051: ['4027', '5051', '19014'], 5052: ['4048', '5052', '19013'], 5053: ['4117', '5053', '19012'], 5054: ['15027', '5054', '9765']}
CodePudding user response:
use the regex as below
import re
regex = r"[0-9][0-9] "
dict1 = {5051: ['/api/1/employees/4027', '5051', '/api/1/seats/19014'],
5052: ['/api/1/employees/4048', '5052', '/api/1/seats/19013'],
5053: ['/api/1/employees/4117', '5053', '/api/1/seats/19012'],
5054: ['/api/1/employees/15027', '5054', '/api/1/seats/9765']}
for i in dict1:
dict1[i] = [re.findall(regex, j)[0] if len(re.findall(regex, j)) >= 1 else j for j in dict1[i]]
print(dict1)
CodePudding user response:
You can apply following regex to achieve desired results
regex = r"[0-9][0-9] "