-2

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

Sam Walker
  • 11
  • 1
  • 2
  • Does this answer your question? [Converting YAML file to python dict](https://stackoverflow.com/questions/13019653/converting-yaml-file-to-python-dict) – Luka Samkharadze Dec 05 '21 at 13:55

2 Answers2

2

You can use the yaml (pyyaml) module, and treat the load as a python dict.

import yaml

document = """
  123:
    a: ''
    b: ''
    c: ''
  456:
    a: ''
    b: ''
    c: ''
"""
yaml.dump(yaml.safe_load(document))
doc = yaml.safe_load(document)

for key in (123, 456, 789):
    try:
        print(f'{key} - {doc[key]} found')
    except KeyError:
        print(f'{key} - not found')
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

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) 
Shay Nehmad
  • 1,103
  • 1
  • 12
  • 25