Home > Back-end >  String split in python for ldap return values
String split in python for ldap return values

Time:04-22

My LDAP Returns values as below

[('CN=b12345,OU=Accounts,DC=mydomain,DC=com', {'Fname': [Jose, Movi'], 'location': [b'London'], 'mail': [b'[email protected]'], 'title': [b'Sales -Exec -Retail']})]
[('CN=h12345,OU=Accounts,DC=mydomain,DC=com', {'Fname': [Lorraine, Moses'], 'location': [b'Boston'], 'mail': [b'[email protected]'], 'title': [b'Sales -ExecIII -Retail']})]
[('CN=o12345,OU=Accounts,DC=mydomain,DC=com', {'Fname': [Andy, Cameron'], 'location': [b'NewYork'], 'mail': [b'[email protected]'], 'title': [b'Customer Support II - Fixed']})]

I would like to split them as below for each entry and print them as below

DisplayName:Jose, Movi
Location:London
Email:[email protected]
Designation:Sales -Exec -Retail

Apologize to me in advance as I'm a beginner in python.

CodePudding user response:

Individual lists

When you define x as:

x = [('CN=b12345,OU=Accounts,DC=mydomain,DC=com',
      {'Fname': ['Jose, Movi'],
       'location': [b'London'],
       'mail': [b'[email protected]'],
       'title': [b'Sales -Exec -Retail']})]

You can print in a key value manner:

for k, v in x[0][1].items():
    try:
        print(f"{k.title()}: {', '.join(a.decode('utf-8') for a in v)}")
    except (UnicodeEncodeError, AttributeError):
        # If you try to decode a regular string
        print(f"{k.title()}: {', '.join(v)}")

Outputs

Fname: Jose, Movi
Location: London
Mail: [email protected]
Title: Sales -Exec -Retail

Or assign custom values for each key:

def printer(k, v):
    try:
        print(f"{k.title()}: {', '.join(a.decode('utf-8') for a in v)}")
    except (UnicodeEncodeError, AttributeError):
        # If you try to decode a regular string
        print(f"{k.title()}: {', '.join(v)}")


for k, v in x[0][1].items():
    if k == "Fname":
        printer("DisplayName", v)
    elif k == "mail":
        printer("Email", v)
    elif k == "title":
        printer("Designation", v)
    else:
        printer(k, v)

Outputs:

Displayname: Jose, Movi
Location: London
Email: [email protected]
Designation: Sales -Exec -Retail

If you are using >= Python3.10 you can use match statements for the custom titles:

for k, v in x[0][1].items():
    match k:
        case "Fname":
            printer("DisplayName", v)
        case "mail":
            printer("Email", v)
        case "title":
            printer("Designation", v)
        case _:
            # Default case
            printer(k, v)

All lists

When you define x as:

x = [[('CN=b12345,OU=Accounts,DC=mydomain,DC=com',
       {'Fname': ['Jose, Movi'],
        'location': [b'London'],
        'mail': [b'[email protected]'],
        'title': [b'Sales -Exec -Retail']})],
     [('CN=h12345,OU=Accounts,DC=mydomain,DC=com',
      {'Fname': ['Lorraine, Moses'],
       'location': [b'Boston'],
       'mail': [b'[email protected]'],
       'title': [b'Sales -ExecIII -Retail']})],
     [('CN=o12345,OU=Accounts,DC=mydomain,DC=com',
      {'Fname': ['Andy, Cameron'],
       'location': [b'NewYork'],
       'mail': [b'[email protected]'],
       'title': [b'Customer Support II - Fixed']})]]

You can edit your examples to be in another for loop for i:

for i in x:
    for k, v in i[0][1].items():
    # Rest of method goes here

If you are strictly working with single element lists, you can change ', '.join(a.decode('utf-8') for a in v) to v.decode('utf-8'). And ', '.join(v) to v

CodePudding user response:

While @Freddy Mcloughlan's answer is good when you have dictionaries, the following might be useful if the data comes from a file. Additionally, it makes use of regex, which is always a good exercise.

import re

file = open("test.file", "r", encoding="utf-8")

entry = file.readline()
while entry not in ["", " "]:
    parsing = re.search(r"\'Fname\': \[([^\]]*)\], \'location\': \[b\'([^\]]*)\'\], \'mail\': \[b\'([^\]]*)\'\], \'title\': \[b\'([^\]]*)\'\]", entry)
    name = parsing.group(1)
    location = parsing.group(2)
    mail = parsing.group(3)
    designation = parsing.group(4)
    print(name, location, mail, designation)
    entry = file.readline()

file.close()
  • Related