0

I have a dictionary in python e.g -

partitions = {'train': ['data/xyz/id-1', 'data/xyz/id-2', 'data/xyz/id-3',......], 
               'validation': ['data/pqr/id-4','data/pqr/id-5',.......]}

I want to replace 'data/xyz ' to 'samples/folder1' for all the values of the key 'train'.

the new values will be

samples/folder1/id-1, samples/folder1/id-2, samples/folder1/id-3 etc

similarly , 'data/pqr' to 'samples/test' for all the values of the key 'validation'.

I am unable to figure out how to do it in a concise way. Any help will be appreciated.

2 Answers 2

2

These are just lists assigned to keys, so you could use a list comprehension to rebuild the list and replacing the values in the strings.

partitions = {
    'train': ['data/xyz/id-1', 'data/xyz/id-2', 'data/xyz/id-3'],
    'validation': ['data/pqr/id-4', 'data/pqr/id-5']
}

print(partitions)
partitions['train'] = [value.replace('data/xyz', 'samples/folder1') for value in partitions['train']]
partitions['validation'] = [value.replace('data/pqr', 'samples/test') for value in partitions['validation']]
print(partitions)

OUTPUT

{'train': ['data/xyz/id-1', 'data/xyz/id-2', 'data/xyz/id-3'], 'validation': ['data/pqr/id-4', 'data/pqr/id-5']}
{'train': ['samples/folder1/id-1', 'samples/folder1/id-2', 'samples/folder1/id-3'], 'validation': ['samples/test/id-4', 'samples/test/id-5']}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! exactly what I was looking for. I wanted to avoid loops .
2

Using simple loop and replace for strings:

partitions = {'train': ['data/xyz/id-1', 'data/xyz/id-2', 'data/xyz/id-3'], 
               'validation': ['data/pqr/id-4','data/pqr/id-5']}
replaces = {'train' : ['samples/folder1', 'data/xyz'] , 'validation' : ['samples/test','data/pqr']}
for key , value in partitions.items():
    temp = []
    for v in value:
        temp.append(v.replace(replaces[key][1], replaces[key][0]))
    partitions[key] = temp
print(partitions)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.