Yaml文件解析迭代值

时间:2018-02-21 18:20:41

标签: python-3.x data-structures yaml pyyaml

我有一个具有以下结构的yaml文件:

User1:
  email: test@test.com
  firstname: test
  lastname: user
  id: AZTEST123
  role: manager
  team: test

我希望能够迭代这个yaml文件并使用我在下面编写的脚本中的值:

def get_users(yaml_file="test.yml"):
  with open(yaml_file, 'r') as stream:
    try:
      data = yaml.load(stream)
      print(data)
    except yaml.YAMLError as exc:
      print(exc)
  return data

def create_user(users):
  for user in users:
    print(user[1])
    try:
      print(user['email'])
      url = 'https://api.test.com/users'
      payload = {
          'user': {
              'type': 'user',
              'name': user['firstname'] + ' ' + user['lastname'],
              'email': user['email'],
              'role': user['role']
          }
      }
      r = requests.post(url, headers=headers, data=json.dumps(payload))
      print ('Status Code: {code}').format(code=r.status_code)
      print (r.json())
      sc.api_call(
        "chat.postMessage",
        channel="#test",
        text="User {user} has been added to Test :tada:".format(user=user['firstname']),
        user="test")
    except requests.ConnectionError as error_message:
      print (error_message)

users = get_users()

create_user(users)

当我从代码中打印收到的print(data)时,它会返回:

{'User1': {'email': 'test@test.com', 'firstname': 'test', 'lastname': 'user', 'id': 'AZTEST123', 'role': 'manager', 'team': 'test'}}

但是当我尝试使用值时:user['firstname']我收到错误:

TypeError: string indices must be integers

当我print(user[0])它返回时:

U

我在这里缺少什么,如何迭代这些项?

1 个答案:

答案 0 :(得分:1)

for循环遍历字典,返回密钥。因此user的值为User1

您想要做的是:

for username in users:
    user = users[username]
    print(user['firstname'])