4
我用以下YAML數據:pyyaml 3.11將字典傳遞給迭代器?
Document:
InPath: /home/me
OutPath: /home/me
XLOutFile: TestFile1.xlsx
Sheets:
- Sheet: Test123
InFile: Test123.MQSC
Server: Testsystem1
- Sheet: Test345
InFile: Test345.MQSC
Server: Testsystem2
Title:
A: "Server Name"
B: "MQ Version"
C: "Broker Version"
Fields:
A: ServerName
B: MQVersion
C: BrokerVersion
和下面的代碼:
import yaml
class cfgReader():
def __init__(self):
self.stream = ""
self.ymldata = ""
self.ymlkey = ""
self.ymld = ""
def read(self,infilename):
self.stream = self.stream = file(infilename, 'r') #Read the yamlfile
self.ymldata = yaml.load(self.stream) #Instanciate yaml object and parse the input "stream".
def docu(self):
print self.ymldata
print self.ymldata['Sheets']
for self.ymlkey in self.ymldata['Document']: #passes String to iterator
print self.ymlkey
for sheets in self.ymldata['Sheets']: #passes Dictionary to iterator
print sheets['Sheet']
for title in self.ymldata['Title']:
print title
for fields in self.ymldata['Fields']:
print fields
的print
輸出是:
{'Fields': {'A': 'ServerName', 'C': 'BrokerVersion', 'B': 'MQVersion'}, 'Document': {'XLOutFile': 'TestFile1.xlsx', 'InPath': '/home/me', 'OutPath': '/home/me'}, 'Sheets': [{'Sheet': 'Test123', 'InFile': 'Test123.MQSC', 'Server': 'Testsystem1'}, {'Sheet': 'Test345', 'InFile': 'Test345.MQSC', 'Server': 'Testsystem2'}], 'Title': {'A': 'Server Name', 'C': 'Broker Version', 'B': 'MQ Version'}}
[{'Sheet': 'Test123', 'InFile': 'Test123.MQSC', 'Server': 'Testsystem1'}, {'Sheet': 'Test345', 'InFile': 'Test345.MQSC', 'Server': 'Testsystem2'}]
X
I
O
Test123
Test345
A
C
B
A
C
B
我無法找出如何控制數據的方法是傳遞給迭代器。我想要的是將其作爲字典傳遞,以便通過密鑰訪問該值。這適用於「表格」,但我不明白爲什麼。該文件沒有描述清楚:http://pyyaml.org/wiki/PyYAMLDocumentation
什麼打印? type(self.ymldata ['Document'])?它的工作對我來說很好 –
你可以嘗試「爲ymlkey in」而不是「for self.ymlkey in」? –
它不會改變任何東西。數據仍然作爲字符串從yamldata傳遞到ymlkey,而不是字典。 – crashdog