I'm newer to Python and am trying to find the most Pythonic way to parse a response from an LDAP query. So far what I have works but I'd like to make it neater if possible. My response data is this:
"[[('CN=LName\\, FName,OU=MinorUserGroup,OU=MajorUserGroup,DC=my,DC=company,DC=com', {'department': ['theDepartment'], 'mail': ['theEmail@mycompany.com']})]]"
Out of that data I'm really only interested in the fields within the {}
so that I can throw it into a dictionary...
"department:theDepartment,mail:theEmail@mycompany.com"
What I'm doing now feels (and looks) really brute-force but works. I've added in extra commenting and output results based on what each step is doing to try and elaborate on this mess.
#Original String
#"[[('CN=LName\\, FName,OU=MinorUserGroup,OU=MajorUserGroup,DC=my,DC=company,DC=com', {'department': ['theDepartment'], 'mail': ['theEmail@mycompany.com']})]]"
#split at open {, take the latter half
myDetails = str(result_set[0]).split('{')
#myDetails[1] = ["'department': ['theDepartment'], 'mail': ['theEmail@mycompany.com']})]]"]
#split at close }, take the former half
myDetails = str(myDetails[1]).split('}')
#myDetails[0] = ["'department': ['theDepartment'], 'mail': ['theEmail@mycompany.com']"]
#split at comma to separate the two response fields
myDetails = str(myDetails[0]).split(',')
#myDetails = ["'department': ['theDepartment']","'mail': ['theEmail@mycompany.com']"]
#clean up the first response field
myDetails[0] = str(myDetails[0]).translate(None, "'").translate(None," [").translate(None,"]")
#myDetails[0] = ["department:theDepartment"]
#clean up the second response field
myDetails[1] = str(myDetails[1]).translate(None," '").translate(None, "'").translate(None,"[").translate(None,"]")
#myDetails[1] = ["mail:theEmail@mycompany.com"]
While I'm a big fan of "if it ain't broke, don't fix it" I'm a bigger fan of efficiency.
EDIT This ended up working for me per the accepted answer below by @Mario
myUser = ast.literal_eval(str(result_set[0]))[0][1]
myUserDict = { k: v[0] for k, v in myUser.iteritems() }