简体   繁体   中英

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. I will display two routes I take below, both being suboptimal.

Yaml file:

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

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)

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? I wish to use the dictionary in my python project instead of creating global variables, etc.

Example:

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

Only calling without loader was depracted. You can always pass SafeLoader to the load function.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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