python - Counting how many specific items exist in a YAML file? -


i'm attempting find out how many "usernames" exist. there two, , can loop on users this, feels clunky. there way how many usernames exist in user?

open('file.yaml', 'r') 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" 

if want counts specific structure:

sum([len(x["users"]) x in d["work"]]) 

for general solution, like:

f = open("test.yaml") d = yaml.safe_load(f)  # d 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):         k, v in d.iteritems():             if k == s: c += 1             c += yaml_count(v, s)     elif isinstance(d, list):         l in d:             c += yaml_count(l, s)      return c  yaml_count(d, "username") # returns 2 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -