Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']})
like image 733
file2cable Avatar asked Feb 08 '23 20:02

file2cable


1 Answers

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
like image 78
Adam Smith Avatar answered Feb 13 '23 00:02

Adam Smith