计算YAML文件中存在多少特定项目?

时间:2013-08-10 06:54:50

标签: python python-2.7 yaml

我试图找出存在多少“用户名”。目前有两个,我可以循环users来获得这个,但这感觉很笨拙。有没有办法让用户中存在多少个用户名?

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"

1 个答案:

答案 0 :(得分:1)

如果您想从特定结构中获取计数:

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

对于一般解决方案,您可以执行以下操作:

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