user2019182
user2019182

Reputation: 315

Python parsing YAML file and printing values

New to Python here. I have a list of users stored in a YAML file that looks like this:

users:
  test:
    dn: dc=test
    cn: test
    objectClass:
      - inetOrgPerson
      - person
      - ldapPublicKey
      - posixAccount
     employeeType: inactive
  test2:
    dn: dc=test
    cn: test2
    objectClass:
      - inetOrgPerson
      - person
      - ldapPublicKey
      - posixAccount
    employeeType: inactive

I want to be able to query this file for all users whos employee type is inactive, and I want to print just the username, which in the example above would be test,test2. I have the following script written but it is returning all users, can someone help point me to what I'm missing?

#!/usr/bin/env python
import os
import yaml
import ldap


with open('ldap_users.yaml', 'r') as file:
    doc = yaml.load(file)

for employeeType, inactive in doc['users'].iteritems():
    print employeeType, inactive

Upvotes: 1

Views: 2307

Answers (1)

jonathanking
jonathanking

Reputation: 652

You're not checking if the employeeType is actually inactive.

After modifying your YAML file to fix the indentation in the last line, I was able to see your problem. You assumed that you were iterating over the employeeType when actually, you were iterating over the different test items. In my code, the info variable is a dictionary that contains the information you require.

info = {'dn': 'dc=test', 'objectClass': ['inetOrgPerson', 'person', 'ldapPublicKey', 'posixAccount'], 'employeeType': 'inactive', 'cn': 'test'}

I've modified your code to show you how to access the employee type. I'm not sure exactly what you would like to print after performing this check, but hopefully that will be apparent to you.

#!/usr/bin/env python
import os
import yaml
import ldap


import yaml
with open('ldap_users.yaml', 'r') as file:
    doc = yaml.load(file)


for test, info in doc['users'].iteritems():
    if info['employeeType'] == 'inactive':
        print test

Upvotes: 1

Related Questions