从嵌套字典/列表Python中提取值集

时间:2015-09-02 18:57:10

标签: python dictionary recursion

我有一个字典teacher,其中包含嵌套的字典列表。我正在尝试使用递归函数为Joe Bloggs的所有同事和同事提取set个名称。

teacher = {'age': 27,
       'name': 'Joe Bloggs',
       'colleagues': [{'age': 34,
                 'name': 'Tim Smith',
                 'colleagues': [{'age': 39,
                           'name': 'Linda Smith',
                           'colleagues': [{'age': 41,
                                     'name': 'Belinda Barker',
                                     'colleagues': []}]},
                          {'age': 33,
                           'name': 'Kelly Brooker',
                           'colleagues': []},
                          {'age': 44,
                           'name': 'Duncan Turnbull',
                           'colleagues': []}]},
                 {'age': 29,
                  'name': 'Jenna French',
                  'colleagues': []}]}

期望的输出:

{'Tim Smith', 'Linda Smith', 'Belinda Barker',
 'Kelly Brooker', 'Duncan Turnbull', 'Jenna French'}

请注意,输出不需要按任何特定顺序排列,因为它是set。与递归函数的情况一样,如果没有实际找到解决方案,很难“取得进展”。到目前为止,我有一个递归函数,它接受两个参数,但不知道如何设置我的函数来生成所需的结果:

def names(teacher, colleagues=None):

1 个答案:

答案 0 :(得分:2)

你可以在集合理解中做到这一点;循环包括colleagues列表中的所有名称以及它们的递归同事名称:

def names(teacher):
    return {name for c in teacher['colleagues'] for name in {c['name']} | names(c)}

您还可以将其表达为直接名称集和递归调用的并集:

def names(teacher):
    direct = {c['name'] for c in teacher['colleagues']}
    return direct.union(*(names(c) for c in teacher['colleagues']))

演示:

>>> def names(teacher):
...     return {name for c in teacher['colleagues'] for name in {c['name']} | names(c)}
... 
>>> names(teacher)
{'Tim Smith', 'Belinda Barker', 'Kelly Brooker', 'Duncan Turnbull', 'Jenna French', 'Linda Smith'}
>>> def names(teacher):
...     direct = {c['name'] for c in teacher['colleagues']}
...     return direct.union(*(names(c) for c in teacher['colleagues']))
... 
>>> names(teacher)
{'Tim Smith', 'Belinda Barker', 'Linda Smith', 'Kelly Brooker', 'Duncan Turnbull', 'Jenna French'}