Search code examples
pythondictionaryactive-directoryldappython-ldap

Python iterating over a datastructure code explanation


I was writing a code in python using ldapsearch and came across this link in rosettacode.org

import ldap

l = ldap.initialize("ldap://ldap.example.com")
try:
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)

    bind = l.simple_bind_s("me@example.com", "password")

    base = "dc=example, dc=com"
    criteria = "(&(objectClass=user)(sAMAccountName=username))"
    attributes = ['displayName', 'company']
    result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes)

    results = [entry for dn, entry in result if isinstance(entry, dict)]
    print results
finally:
    l.unbind()

I am unable to understand this piece of code here results = [entry for dn, entry in result if isinstance(entry, dict)]

  • I don't see dn defined in the above code, so where does it take from?
  • What does isinstance(entry, dict) do?

When I tries to execute this, I can see that this returns a list of all ldap entries, with its corresponding attributes associated with it. The initial result is also returning a list. Can someone please explain what the results code does?


Solution

  • somelist = [entry for dn, entry in result if isinstance(entry, dict)] 
    translates to 
    
    for entry, dn in result:
       if isinstance(entry, dict): # this checks if entry is of type dictionry
          somelist.append(entry)