4:
- a: [0.6511928334730416, -0.6444996859128429, 0.40070930065859994]
b: [-70.26386506067132, 19.563101216582368, 315.91419304402643]
c: [462, 429, 401, 389]
d: 1
5:
- e: [0.6511928334730416, -0.6444996859128429, 0.40070930065859994]
f: [-70.26386506067132, 19.563101216582368, 315.91419304402643]
g: [462, 429, 401, 389]
h: 1
这是我的yml格式,我必须从中提取密钥c和g的值并创建一个csv文件。我是python的新手。
任何人都可以在这里指导我
提前谢谢
答案 0 :(得分:0)
通过循环,你可以做,但这只是一个你也可以更好的想法
试试这个: -
import yaml
MyDict = yaml.load(open('example.yaml'))
key = ['c','g']
for i in MyDict.values():
for j in i:
for k in key:
if k in j:
print(j.get(k))
答案 1 :(得分:0)
如果您转换为dict的yaml与此类似:
d = {4:
{
'a': [0.6511928334730416, -0.6444996859128429, 0.40070930065859994],
'b': [-70.26386506067132, 19.563101216582368, 315.91419304402643],
'c': [462, 429, 401, 389],
'd': 1
},
5:
{'e': [0.6511928334730416, -0.6444996859128429, 0.40070930065859994],
'f': [-70.26386506067132, 19.563101216582368, 315.91419304402643],
'g': [462, 429, 401, 380],
'h': 1
}
}
您可以尝试将以下代码转换为CSV格式:
import csv
import itertools
# taking only the values of keys 'c' and 'g'
li = [i[j] for i in d.values() for j in i.keys() if j == "c" or j == "g"]
# the above list of list making a flat list for better result
merged = list(itertools.chain.from_iterable(li))
with open("filename.csv",'w') as myfile:
wr = csv.writer(myfile, lineterminator='\n')
# If you want first list to csv you can use li instead of merged
wr.writerow(merged)
答案 2 :(得分:0)
我已经尝试并测试了这个
import yaml
with open(r'test.yaml') as file:
documents = yaml.full_load(file)
for item, doc in documents.items():
print(item, ":", doc)