Search code examples
pythonyamlpyyaml

How do I check if a key exists in a yaml file Python


I'm trying to check if a username exists in a yaml file

the format of my file goes as:

random_uuid:
    username: ""
random_uuid:
    username: ""
random_uuid:
    username: ""

I'm still unsure how to do it after googling as it must look through all uuids


Solution

  • If this is the structure of your YAML file, simply iterate on all the values until you find what you're looking for. Assuming that the file is in test.yaml:

    #!/usr/bin/env python
    import yaml
    
    FILE_PATH = "test.yaml"
    LOOKING_FOR_THIS_USER = "Shay"
    
    with open(FILE_PATH, "r") as stream:
        try:
            loaded_yaml = yaml.safe_load(stream)
            for k, v in loaded_yaml.items():
                print(f"{k=}: {v=}")
                if v['username'] == LOOKING_FOR_THIS_USER:
                    print(f"Found it! {k} is the user we looked for.")
        except yaml.YAMLError as exc:
            print(exc)