Pulling elements from dict embedded in a list in Python 3

300 views Asked by At

TL:DR version:

Trying to pull a list out of a dict (Edited out: tuple) based on it's index. i.e. {'a': [1,2], 'b':[3,4]} ... trying to figure out how to return the list associated with a or b respectively.

Answered:

MyDict = {'a': [1,2], 'b':[3,4]}

print(MyDict['a'])

[1,2]

print(MyDict['b'])

[3,4]

Actual version with context:

python3-ldap returns values for attributes of LDAP accounts in a data structure with which I am not familiar. It looks like:

{'department': ['DepartmentName'], 'memberOf': ['CN=example,OU=of,DC=domain,DC=com', 'CN=example,OU=of,DC=domain,DC=com']}

I am trying to pull out the values associated with department and the memberOf separately. I think this is a tuple with an embedded tuple where the second element of the embedded tuple is a list... but I'm not sure so I haven't been able to figure out how to parse the data.

I created a class to eventually drop the users into. Code for indexing:

class Associates:
    def __init__(self, index, name, department, membergrp):
        self.i = index
        self.n = name
        self.d = department
        self.m = membergrp

Here is the code that does the search:

        result = c.search(searchDC, criteria, SEARCH_SCOPE_WHOLE_SUBTREE, attributes = ['department','memberOf'])
        if result:
            for r in c.response:
                if (r['type'] == 'searchResEntry'):
                    a.append(Associates(len(a)+1,(r['dn']), r['attributes'],r['attributes']))
                else:
                    pass

...where 'a' is an empty list.

Answered:

Cannot change the query, must contain r['attributes'] for both selections; however, when the selections are returned in r, they can be parsed as...

print ('Department is:', a[k].d['department'])
print ('Member groups are: ', a[k].m['memberOf'])

Where k is the index of the list.

1

There are 1 answers

1
Terry Jan Reedy On BEST ANSWER

{'a': [1,2], 'b':[3,4]}, and the LDAP data structure {'department': ['DepartmentName'], 'memberOf': ['CN=example,OU=of,DC=domain,DC=com', 'CN=example,OU=of,DC=domain,DC=com']} are key-value dicts. Values are retrieved by key.

d = {'department': ['DepartmentName'],
     'memberOf': ['CN=example,OU=of,DC=domain,DC=com',
                  'CN=example,OU=of,DC=domain,DC=com']}
dept = d['department']  # access by key
mem = d['memberOf']
print("dept = {}\nmem = {}".format(dept, mem))

If you have not, I recommend you read the tutorial and library manual sections on dictionaries.