Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use one line code to convert the dict to a string?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading