如何将对象转换成字典?

时间:2019-02-15 12:55:21

标签: python python-2.7 yaml

我从打开并读取YAML文件的函数中返回了对象<generator object load_all at 0x000000000309AB40>。从此返回中,我需要创建一个有组织的文件字典。

#FILE YAML TEST.yaml   
---
MAIN:
  Name: Jaqueline
  Age: 30
  City: New York
OTHER:
  State: True

______________________________________________________
#PYTHON
from ruamel.yaml import YAML
from pathlib import Path


def file_yaml():
   yaml = YAML()
   stream = Path('TEST.yaml')
   yaml_conf=yaml.load_all(stream)
   print(yaml_conf)

   return yaml_conf


yaml=file_yaml()
dictionary=?????

yaml是一个对象<generator object load_all at 0x000000000309AB40>

如果我做:     ...

yaml=file_yaml()
dictionary =dict(yaml)
print dictionary

我有:{'MAIN': 'OTHER'}。我从档案中丢失了很多信息! 如何使用文件数据创建正确的字典?

1 个答案:

答案 0 :(得分:3)

对我来说很好:

import yaml

with open('random.yaml', 'r') as fin:
    yml = yaml.safe_load(fin)

yml


{'MAIN': {'Name': 'Jaqueline', 'Age': 30, 'City': 'New York'},
 'OTHER': {'State': True}}