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):
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)