Home > Back-end >  How to use one line code to convert the dict to a string?
How to use one line code to convert the dict to a string?

Time:01-14

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?

CodePudding user response:

I'd only make two small changes:

  1. Use f-strings
  2. 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)
  •  Tags:  
  • Related