Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check existence of YAML key

Tags:

python

yaml

I use PyYAML to work with YAML files. I wonder how I can properly check existence of some key? In the example below title key is present only for list1. I want to process title value properly if it exists, and ignore if it is not there.

list1:
    title: This is the title
    active: True
list2:
    active: False
like image 674
Sergei Basharov Avatar asked Feb 13 '12 12:02

Sergei Basharov


People also ask

How to check if a YAML file is valid?

There are many ways to check yaml file validation yamllint is one of the programs to check via command line In python, pyyaml package provides yaml validation with yamllint using python command, we can validate and print the validation logs to console IDE are a popular code editor to write and validate the code

Can We chain a YAML validator?

This tool cannot be chained. Yaml validator tool What is a yaml validator? This YAML validator checks the syntax of YAML (Yet Another Markup Language) data. If there are mistakes, then it returns a detailed syntax error message that explains what happened. It also tells the position of error and displays the conflicting snippet.

How to use yamllint to check the code via command line?

yamllint is one of the programs to check via command line In python, pyyaml package provides yaml validation with yamllint using python command, we can validate and print the validation logs to console IDE are a popular code editor to write and validate the code

Where is YAML used in real life?

It is most often used in configuration files of servers and software applications. Clark Evans proposed the spec in 2001 as the result of an effort to simplify XML. According to his resume, at the time he conceived of YAML he was working with Python, which likely influenced the syntax of YAML as an indentation-based language.


2 Answers

Once you load this file with PyYaml, it will have a structure like this:

{
'list1': {
    'title': "This is the title",
    'active': True,
    },
'list2: {
    'active': False,
    },
}

You can iterate it with:

for k, v in my_yaml.iteritems():
    if 'title' in v:
        # the title is present
    else:
        # it's not.
like image 100
Ned Batchelder Avatar answered Sep 17 '22 14:09

Ned Batchelder


If you use yaml.load, the result is a dictionary, so you can use in to check if a key exists:

import yaml

str_ = """
list1:
    title: This is the title
    active: True
list2:
    active: False
"""

dict_ = yaml.load(str_)
print dict_

print "title" in dict_["list1"]   #> True
print "title" in dict_["list2"]   #> False
like image 42
PabloG Avatar answered Sep 19 '22 14:09

PabloG