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

Elagent way to concat all dict values together with a string carrier as a single string in Python

The objective is to concat all values in a dict into a single str.

Additionally, the \r\n also will be appended.

The code below demonstrates the end result.

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

However, I am looking for an elegant alternative than the proposed code below.

d=dict(idx='1',sat='so',sox=[['x1: y3'],['x2: y1'],['x3: y3']],mul_sol='my love so')

s=''
for x in d:
    if x=='sox':
        for kk in d[x]:
            s=s +kk[0] +'\r\n'
    else:

        s=s +d[x]+'\r\n'
print(s)

>Solution :

Use two generators, one for d['sox'] and another for everything else, and then use join() to concatenate strings.

s = ''.join(kk[0] for kk in d['sox']) + '\r\n'
s += '\r\n'.join(val for key, val in d.items() if key != 'sox')
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