0

TL:DR 版本:

试图根据它的索引从字典中拉出一个列表(已编辑:元组)。即{'a': [1,2], 'b':[3,4]} ...试图弄清楚如何分别返回与 a 或 b 关联的列表。

回答:

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

print(MyDict['a'])

[1,2]

print(MyDict['b'])

[3,4]

带上下文的实际版本:

python3-ldap 在我不熟悉的数据结构中返回 LDAP 帐户的属性值。看起来像:

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

我正在尝试分别提取与部门和 memberOf 关联的值。我认为这是一个带有嵌入式元组的元组,其中嵌入式元组的第二个元素是一个列表......但我不确定,所以我无法弄清楚如何解析数据。

我创建了一个类,最终将用户放入其中。索引代码:

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

这是执行搜索的代码:

        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

...其中 'a' 是一个空列表。

回答:

无法更改查询,两个选择都必须包含 r['attributes'];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'])

其中 k 是列表的索引。

4

1 回答 1

1

{'a': [1,2], 'b':[3,4]},而 LDAP 数据结构{'department': ['DepartmentName'], 'memberOf': ['CN=example,OU=of,DC=domain,DC=com', 'CN=example,OU=of,DC=domain,DC=com']}是键值字典。通过键检索值。

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))

如果您还没有,我建议您阅读有关词典的教程和库手册部分。

于 2014-11-12T22:42:11.107 回答