Search code examples
pythondictionarydata-structuresdefaultdict

python defaultdict how can I check if a nested key exists or is [] without creating the key


There are 3 types of entries in a nested defaultdict a of structure a=defaultdict(lambda: defaultdict(list)).

for i in a:
    print a[i]

defaultdict(<type 'list'>, {'ldap_uidnumber': [['10002']], 'file': ['ABC', 'xyz']})
defaultdict(<type 'list'>, {'ldap_uidnumber': [], 'file': ['abcd']})
defaultdict(<type 'list'>, {'file': ['/home/testuser/.ssh/id_rsa.pub']})
  1. How do I filter out the second one, with ldap_uidnumber: []?
  2. How do I filter out the third one without the key ldap_uidnumber at all?

The code I tried:

for i in a:
    if a[i]["ldap_uidnumber"] and a[i]["ldap_uidnumber"] == []:
        print i

But that is not printing anything, but creating the key in the third value after this code, and looks like

defaultdict(<type 'list'>, {'ldap_uidnumber': [], 'file': ['/home/testuser/.ssh/id_rsa.pub']})

Solution

  • Checking for membership using in doesn't create the key in a defaultdict. I would recommend that.

    for i in a:
        if "ldap_uidnumber" in a[i] and      # shortcircuit here in your 3rd el
                not a[i]['ldap_uidnumber']:  # fail here in your 1st el
            # do something