Joseph
Joseph

Reputation: 13

Python 3 , load key value from Yaml as varible

I am looking to create a new folder for each item under the folders key as below. Yaml file is as below

---
software:
  dir: C:/software
folders:
  - bob:
      ip:
        - "192.168.1.5"
        - "192.168.1.6"
      password:
        - kdhkfjhkjdkjfjsikd
  - alice:
      ip:
        - "192.168.1.3"
      password:
        - hfsdkljfdhkjsfkjfsd

Python Code

from sys import path
import requests
import os
import yaml

with open('config.yaml') as f:
    config = yaml.load(f, yaml.loader.FullLoader)+

for i in config["folders"]:
    for f in i.values():
        print(i)

I am just using print as its easier to understand the data. This returns

{'bob': {'ip': ['192.168.103.5', '192.168.103.6'], 'password': ['kdhkfjhkjdkjfjsikd']}}
{'alice': {'ip': ['192.168.105.3'], 'password': ['hfsdkljfdhkjsfkjfsd']}}

now what I want to happen is just return the folder names, e.g. bob, alice. I have tried the below with no luck, thank you.

for i in config["folders"]:
for f in i.values():
    print(i[0])

which returns

print(i[0])
KeyError: 0

Upvotes: 1

Views: 991

Answers (3)

user12033367
user12033367

Reputation:

try this:

import yaml

with open('yamer.yaml') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

data = data.get('folders')

for x in data:
    for i in x.keys():
        print(i)

It basically "gets" the dictionary with the key "folders" from data dict. Then we can iterate through it as shown above and print the folder names. You can create a list and start appending the names (strings) to it if needed. Thank you!

Upvotes: 0

AnsFourtyTwo
AnsFourtyTwo

Reputation: 2518

You should always be aware of what type the variables are. You can check this using the type() function.

Some examples:

  • type(config) should give you <class 'dict'>
  • type(config["folders"]) should give you <class 'list'>, as it is a list of dictionaries.

When you do

for i in config["folders"]:
    print(i[0])

every i in the loop corresponds to an item of list config["folders"], which itself is a dictionary. Therefore, with i[0], you try to access the dictionary item with key 0, which does not exist.

Instead, you probably want to print the first key of the dictionary with:

for i in config["folders"]:
    print(list(i.keys())[0])

Upvotes: 0

JMA
JMA

Reputation: 813

You can get the folder names with:

import yaml

with open('config.yaml') as f:
    config = yaml.load(f, yaml.loader.FullLoader)

folder_names = [list(folder)[0] for folder in config["folders"]]

Upvotes: 1

Related Questions