Python - 使用 PyGitHub get_contents 从 github 下载 yaml 文件并尝试将其转换为字典
Python - downloading a yaml file from github using PyGitHub get_contents and trying to convert it to dict
我有一个 python 脚本,它使用 repo.get_contents 从 repo 下载 file_content。
所以我用了 -
contents = repo.get_contents(
'./some_file.yaml', ref='master').decoded_content.decode()
现在我将 yaml 文件的内容作为字符串 -
\nkey1:\n-a\n-b-n-c\nkey2
如何将它转换为带有键和值的字典?
我可以使用该功能将它拉到 dict 吗?或以某种方式转换此字符串?
您可以使用PyYAML
pip install pyyaml
运行 您的代码如下所示:
import yaml
yml_file = #your yml file
json_file = yaml.load(yml_file)
这可能是一个重复的问题。
import yaml
dct = yaml.safe_load('''
name: John
age: 30
automobiles:
- brand: Honda
type: Odyssey
year: 2018
- brand: Toyota
type: Sienna
year: 2015
''')
assert dct['name'] == 'John'
assert dct['age'] == 30
assert len(dct["automobiles"]) == 2
assert dct["automobiles"][0]["brand"] == "Honda"
assert dct["automobiles"][1]["year"] == 2015
我有一个 python 脚本,它使用 repo.get_contents 从 repo 下载 file_content。 所以我用了 -
contents = repo.get_contents(
'./some_file.yaml', ref='master').decoded_content.decode()
现在我将 yaml 文件的内容作为字符串 - \nkey1:\n-a\n-b-n-c\nkey2
如何将它转换为带有键和值的字典? 我可以使用该功能将它拉到 dict 吗?或以某种方式转换此字符串?
您可以使用PyYAML
pip install pyyaml
运行 您的代码如下所示:
import yaml
yml_file = #your yml file
json_file = yaml.load(yml_file)
这可能是一个重复的问题。
import yaml
dct = yaml.safe_load('''
name: John
age: 30
automobiles:
- brand: Honda
type: Odyssey
year: 2018
- brand: Toyota
type: Sienna
year: 2015
''')
assert dct['name'] == 'John'
assert dct['age'] == 30
assert len(dct["automobiles"]) == 2
assert dct["automobiles"][0]["brand"] == "Honda"
assert dct["automobiles"][1]["year"] == 2015