将Yaml文件保存到生成器对象的字典python中

时间:2019-12-27 15:22:56

标签: python dictionary import yaml

将YAML文件保存到python字典时遇到很多问题。我将在下面显示两条路线,均不理想。

Yaml文件:

modules:
    module_1: True
    module_2: True
    module_3: False
scenarios:
    constant:
        start_date: "2018-09-30"
        end_date: "2019-09-30"
    adverse:
        start_date: "2019-09-30"
        end_date: "2022-09-30"

途径1:直接将YAML文件保存到字典中,而无需指定现在已贬值的加载器

import yaml
filepath = "C:\\user\\path\\file.yaml"
_dict = yaml.load(open(filepath))
print(type(_dict))
>>> <class 'dict'>

error message: Calling yaml.load() without loader=... is depreciated, as it is unsafe

路线2:作为生成器加载(不可订阅)

import yaml
filepath = "C:\\user\\path\\file.yaml"
document = open(filepath, "r")
dictionary = yaml.safe_load_all(document)

print(type(dictionary)
>>> <generator object>

print(dictionary["modules"]["module_1"]
>>> generator object is not subscriptable

是否可以安全地将yaml文件导入字典?我希望在我的python项目中使用字典,而不是创建全局变量等。

示例:

if _dict["modules"]["module_1"]:
    # Do something

1 个答案:

答案 0 :(得分:2)

仅在没有加载程序的情况下进行调用。您始终可以将SafeLoader传递给加载功能。

import yaml

with open(filepath, 'r') as stream:
    dictionary = yaml.load(stream, Loader=yaml.SafeLoader)

这应该返回您的字典。

编辑:

对于yaml.safe_load_all,您只需调用generator.__next__()即可获得字典。

import yaml
filepath = "C:\\user\\path\\file.yaml"
document = open(filepath, "r")
generator = yaml.safe_load_all(document)
dictionary = generator.__next__()

我建议您使用第一个选项。