Don't understand cause of TypeError while parsing yaml file

Viewed 156

When trying to read this yaml file in python, I'm getting a TypeError for index.

vehicles:
    fourwheeler:
        - car
        - truck 
def main():
    with open('veh_info.yaml') as file:
       info = yaml.load(file, Loader=yaml.FullLoader)
        
    for veh in info:                
        for fourwheeler in veh["fourwheeler"]:
            if fourwheeler == "car":   
                print("It's a car")

The error that is coming is:

TypeError: string indices must be integers
3 Answers

You have to reference the key veh from info like this,

for veh in info:
    for forwheeler in info[veh]:
        if forwheeler == "car":
            print("It's a car")

First reference the fourwheeler list by indexing the yaml content, then loop over it to check the list entry values:

import yaml


def main():
    with open('veh_info.yaml') as file:
       info = yaml.load(file, Loader=yaml.FullLoader)

    for vehicle in info["vehicles"]["fourwheeler"]:
        if vehicle == "car":
            print("It's a car")


main()

Producing:

It's a car

When you load the .yaml input file, its content is returned as a dictionary, which you named info in your code. Dictionaries are a set of key–value pairs. The keys are usually strings, such as 'vehicles' here. The values may be anything, even another (nested) dictionary.

When you iterate over a dictionary, such as in the line for veh in info, it returns the keys — but not the values. If you want to iterate over the values, you need to call info.values() instead. So with this one change, your code works as expected.

Now, the reason you see that particular error message is because the key veh is just a string: 'vehicles'. You can index a string, but only with an integer number. For example, 'vehicles'[0] gives you the first character in that string: 'v'. You cannot index a string with another string, the way you would index a dictionary, like the value corresponding to that key veh that you actually meant to access. Hence that error.

Related