I have this list
of dict
ionaries and want to convert it into .yml
file
input = [
{
'id': 1,
'coordinates': [
[34, 31],
[235, 31],
[34, 97],
[235, 97]
]
},
{
'id': 2,
'coordinates': [
[1028, 31],
[1248, 31],
[1028, 104],
[1248, 104]
]
}
]
This is my code:
import json
import yaml
coord = [{'id': 1, 'coordinates': [[34, 31], [235, 31], [34, 97], [235, 97]]}, {'id': 2, 'coordinates': [[1028, 31], [1248, 31], [1028, 104], [1248, 104]]}]
print(coord)
ff = open('data.yml', 'w')
yaml.dump(coord, ff, default_flow_style=False)
ydump = yaml.dump(coord, default_flow_style=False)
print ('ydump=',ydump)
f.close()
But im getting this output :-
ydump= - coordinates:
- - 34
- 31
- - 235
- 31
- - 34
- 97
- - 235
- 97
id: 1
- coordinates:
- - 1028
- 31
- - 1248
- 31
- - 1028
- 104
- - 1248
- 104
id: 2
Whereas required output is :-
===================UPDATE==================
I tried this code which might work
with open("test.yml", "w ") as output:
output.write("-\n id: " str(id) "\n coordinates: ["
"[" str([xywh[0]) "," str(xywh[1]) "]," "]]\n")
"[" str(xywh[0] xywh[2]) "," str(xywh[1]) "],"
"[" str(xywh[0]) "," str(xywh[1] xywh[3]) "],"
"[" str(xywh[0] xywh[2]) "," str(xywh[1] xywh[3]) "]]\n")
But getting this error :-
"[" str([xywh[0]) "," str(xywh[1]) "]," "]]\n")
^
SyntaxError: invalid syntax
CodePudding user response:
Thanks a lot everyone. This snippet solved my problem :-
with open("test.yml", "w ") as output:
output.write("-\n id: " str(ctr) "\n coordinates: ["
"[" str(xywh[0]) "," str(xywh[1]) "],"
"[" str(xywh[0] xywh[2]) "," str(xywh[1]) "],"
"[" str(xywh[0]) "," str(xywh[1] xywh[3]) "],"
"[" str(xywh[0] xywh[2]) "," str(xywh[1] xywh[3]) "]]\n")
CodePudding user response:
I tried to copy-paste your JSON
string into
This probably means that the standard .yml
file doesn't format Python list
s that way.
CodePudding user response:
Try this: add sort_keys=False
ydump = yaml.dump(coord, default_flow_style=False, sort_keys=False)