Q:

Counting how many specific items exist in a YAML file?

I'm attempting to find out how many "usernames" exist. Currently there are two, and I can loop over users to get this, but that feels clunky. Is there a way to get how many usernames exist in user?
open('file.yaml', 'r') as f:
  file = yaml.safe_load(f)

  # count number of usernames in user...?

file.yaml:
host: "example.com"
timeout: 60

work:
-
  processes: 1
  users:
  -
    username: "me"
  -
    username: "notme"

A:

If you want to get counts from your specific structure:
sum([len(x["users"]) for x in d["work"]])

For a general solution, you could do something like:
f = open("test.yaml")
d = yaml.safe_load(f)

# d is now a dict - {'host': 'example.com', 'work': [{'processes': 1, 'users': [{'username': 'me'}, {'username': 'notme'}]}], 'timeout': 60}

def yaml_count(d, s):
    c = 0
    if isinstance(d, dict):
        for k, v in d.iteritems():
            if k == s: c += 1
            c += yaml_count(v, s)
    elif isinstance(d, list):
        for l in d:
            c += yaml_count(l, s) 
    return c

yaml_count(d, "username") # returns 2

