簡體   English   中英

Python添加到字典鍵,來自yaml的值對

[英]Python add to Dictionary key, value pair from yaml

我如何循環解析yaml以使用format key: value列出。 Yaml文件:

   dbconfig:
     host: localhost
     database: db_test
     username: user
     password: 12345

我所做的:

with open('config.yml', 'r') as yml:
    cfg = yaml.load(yml)
    db_list = {}
    for key, value in cfg['dbconfig']:
        db_list['key'] = value

但這不起作用。

使用db_list[key] = value而不是'db_list['key'] = value'

db_list[key] = value將使用key中的任何內容作為字典鍵,而db_list['key'] = value'將使用字符串'key'作為字典鍵。

有關更多信息,請查看字典中的Python文檔

我假設您收到ValueError: too many values to unpack 您需要做的是遍歷一個元組列表而不是字典。 要將字典中的值作為鍵值元組獲取,請使用items()方法。

with open('config.yml', 'r') as yml:
    cfg = yaml.load(yml)
    db_list = {}
    for key, value in cfg['dbconfig'].items():
        db_list[key] = value # you need to use the variable key here

我不確定您要實現的目標,因為最后,您的db_list將與cfg['dbconfig']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM