Keeping punctuation in string while getting dictionary values

Viewed 62

I have the below code and looking to get abc, cde as output. I have tried to convert the Nones to empty strings using str(i or ' ') for i in m and got abc cde as output. Is it possible to isolate the comma , such that the output would be abc, cde?

d = {'1':'a', '2':'b', '3':'c', '4':'d', '5':'e'}
s = '123, 345'
m = [d.get(i) for i in s]
print(''.join(map(str, m)))

# output -> abcNoneNonecde

I managed to get the desired output by adding ',':',' to the dictionary, like below. But wondering if there's another way of achieving the same?

d = {'1':'a', '2':'b', '3':'c', '4':'d', '5':'e'}
d[','] = ','
s = '123, 345'
m = [d.get(i) for i in s]
output = [str(i or ' ') for i in m]
print(''.join(map(str, output)))

# output -> abc, cde
2 Answers

Use i as the default value for get.

d = {'1':'a', '2':'b', '3':'c', '4':'d', '5':'e'}
s = '123, 345'
m = [d.get(i, i) for i in s]
print(''.join(map(str, m)))

Or all in one line.

print(''.join(d.get(i, i) for i in s))

We can drop the mapping to str because all values are already a string.

Related