Search code examples
pythonstringpython-3.xtuplesdataformat

Extract string from tuple embedded in a list, Python 3


Apologies in advance if this question has already been asked, have done some searching but no luck.

TL;DR: Trying to pull second piece of a tuple out as a string.

I am building a script with python3 that pulls information from LDAP and returns what is hopefully actionable data.

def GetMembersWDept():
    i2 = input('Please input the department number. Examples: 2410, 2417\n')
    criteria = '(&(objectClass=User)(department=' + i2 + '*))'
    print ('Search criteria set to: \t\t' + criteria)
    searchDC = 'dc=example,dc=com'
    print ('Searching location: \t\t\t' + searchDC)
    print ()
    out = []
    result = c.search(searchDC, criteria, \
        SEARCH_SCOPE_WHOLE_SUBTREE, attributes = ['department'])  \
        # request a few object from the ldap server
    if result:
        for r in c.response:
            if (r['type'] == 'searchResEntry'):
                out.append(r['dn'])
                out.append(r['attributes']) # comes out in tuple form
            else:
                pass
    else:
        print('result', conn.result)
    return out

This works well for pulling out the CN of the members in that department but not for extracting whatever additional information, in this case the department, is appended.

A sample output is:

Search criteria set to: (&(objectClass=User)(department=2417*)) Searching location: dc=ple,dc=com

['CN=First Last,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}, 'CN=Another Person,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}]

How can I pull out the second portion of the tuple, i.e. '1234', as a string instead? The endgame here would be to format the data as:

[First Last, 1234, Another Person, 1234]

... so I can use it in another function that compares the department and returns the name if conditions are not met.


Solution

  • If output is:

    ['CN=First Last,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}, 'CN=Another Person,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}]
    

    then you can set that equal to newresult and do:

    print(list(newresult[1].values())[0][0])
    

    This assumes that the element in the list with the department is always in position 1, that the dictionary always has 1 value to it, and that the department number you want is the only item in the list.