Max Power
Max Power

Reputation: 83

Python add to Dictionary key, value pair from yaml

How I can parse yaml in cycle to list with format key: value. Yaml file:

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

What I do:

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

But this do not work.

Upvotes: 1

Views: 4174

Answers (2)

Yanick Nedderhoff
Yanick Nedderhoff

Reputation: 1234

Use db_list[key] = value instead of 'db_list['key'] = value'.

db_list[key] = value will use whatever is in key as the dictionary key, while db_list['key'] = value' will use the string 'key' as the dictionary key.

Have a look at the the Python docs on dictionaries for more info.

Upvotes: 2

M472
M472

Reputation: 330

I assume you get a ValueError: too many values to unpack. What you need to do is to iterate over a list of tuples instead of the dictionary. To get the values in the dictionary as key-value tuples use the items() method.

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

I am not sure what you are trying to achieve because in the end, your db_list will be the same as cfg['dbconfig'].

Upvotes: 0

Related Questions