yaml文件与字典之间转换
pip install pyyaml
def save_dict_to_yaml(dict_value: dict, save_path: str): """dict保存为yaml""" with open(save_path, 'w') as file: file.write(yaml.dump(dict_value, allow_unicode=True)) def read_yaml_to_dict(yaml_path: str, ): """yaml读取出来到字典""" with open(yaml_path) as file: dict_value = yaml.load(file.read(), Loader=yaml.FullLoader) return dict_value
样例
temp_dic = { "name":"ws", "age":"18", "love":["吃","喝","玩","乐"] } temp_str = yaml.dump(temp_dic,allow_unicode=True) print(temp_str) ------------------- age: '18' love: - 吃 - 喝 - 玩 - 乐 name: ws -------------------
思考:你看他排序都是英文字母排序的,我能否改变他的排序方式呢
是的,yaml.dump可以使用参数控制输出的顺序。可以通过设置参数default_flow_style=False来输出字典的键值对按照字典的顺序排列,而不是按照随机顺序排列。例如: ```python import yaml data = {'c': 1, 'a': 2, 'b': 3} # 默认情况下,yaml.dump按照随机顺序输出字典的键值对 print(yaml.dump(data)) # 设置default_flow_style=False,按照字典的顺序输出字典的键值对 print(yaml.dump(data, default_flow_style=False)) ``` 输出结果为: ``` {a: 2, c: 1, b: 3} a: 2 c: 1 b: 3 ```
-----------------------------------------------------------------------------------------------------------------------------------------