简体   繁体   English

将yaml文件保存到生成器对象到字典python

[英]Save a yaml file to a generator object to a dictionary python

I am having a lot of issues saving a YAML file to a python dictionary.我在将 YAML 文件保存到 python 字典时遇到很多问题。 I will display two routes I take below, both being suboptimal.我将在下面展示我采用的两条路线,这两条路线都不理想。

Yaml file: 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"

Route 1: Saving YAML file directly to a dictionary without specifying a loader which is now depreciated路线 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

Route 2: Loading in as a generator (which is not subscriptable)路线 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

Is there a way I can import my yaml file into a dictionary safely?有没有办法可以安全地将我的 yaml 文件导入字典? I wish to use the dictionary in my python project instead of creating global variables, etc.我希望在我的 python 项目中使用字典而不是创建全局变量等。

Example:例子:

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

Only calling without loader was depracted.只有在没有加载程序的情况下调用被弃用。 You can always pass SafeLoader to the load function.您始终可以将 SafeLoader 传递给加载函数。

import yaml

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

This should return your dictionary.这应该返回您的字典。

edit:编辑:

And as for yaml.safe_load_all , you only need to call generator.__next__() to obtain the dictionary.而对于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__()

I would recomend the first option for your use.我会推荐第一个选项供您使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM