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

print a list of dict and corresponding key as comma seperated values

I have following dict:

data = {
        'A': [{1.0: 133.0}, {4.0: 126.0}], 
        'B': [{1.0: 153.0}, {4.0: 16.0}],
        'C': [{1.0: 9.0}, {4.0: 12.0}]
       }

I need the output as follows:

A, 1.0, 133.0
A, 4.0, 126.0
B, 1.0, 153.0
B, 4.0, 16.0
C, 1.0, 9.0
C, 4.0, 12.0

This is my attempt (working):

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

with open("super.csv", "w") as f:
    for k, v in data.items():
        for a in v:
            f.write(k + ", " + "".join('{}, {}'.format(k1,v1) for k1,v1 in a.items()) + "\n")

I am unable to make this better (more concise), please help. Can I avoid using join?

>Solution :

You can also use k1,v1 = list(a.items())[0] instead of ((k1,v1),) = a.items()
and also you can use print(f"{k}, {k1}, {v1}",file=f) so that "\n" already impleminted

with open("super.csv", "w") as f:
    for k, v in data.items():
        for a in v:
            ((k1,v1),) = a.items()
            print(f"{k}, {k1}, {v1}",file=f)
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