d = {1:'a', 2:'b'}
#s = '1|a;2|b'
s = ';'.join([str(k)+'|'+d[k] for k in d])
Is there a better way to do this conversion?
>Solution :
I’d only make two small changes:
- Use f-strings
- Use a generator expression instead of a list comprehension, which would remove the need to hold all the values in memory prior to joining. It’s not really a big deal unless you have thousaaaands of key/value pairs, though.
s = ';'.join(f'{k}|{d[k]}' for k in d)