检索嵌套键列表的好方法?

时间:2017-03-23 17:04:59

标签: python dictionary nested

我正在使用安然电子邮件数据集。它是一本字典字典,其中原始字典中的每个名称都是另一组特征的关键字。只是为了表明它看起来像这样。

enron = {'Mark' : {'salary': 10, 'employed': 'yes'}, 'Ted' : {'salary': 5, 'employed': 'yes'}

除了真正的数据集当然要大得多,还有更多的功能。如果我想获得功能列表,我会做类似的事情:

for key in enron['Mark']:
    print key

这个工作得很好,但似乎很懒。 Python中是否有一个更通用的函数可以自动到达某个字典层?我担心有一天我可能不得不使用多级词典,而且我不必写下以下的变体:

for key in dic['a']['b']['c']

一遍又一遍。

2 个答案:

答案 0 :(得分:1)

这与你想要的相似吗?

enron = {'Mark': {'salary': 10, 'employed': {'boogie': 'obviously'}}, 
        'Ted': {'salary': 5, 'employed': 'yes'}}


def get_nested_keys(dictionary, dict_keys):
    return list(recursive_nested_keys(dictionary, dict_keys))


def recursive_nested_keys(dictionary, dict_keys):
    if len(dict_keys) < 2:
        return dictionary[dict_keys[0]].keys()
    if len(dict_keys) > 1:
        return recursive_nested_keys(dictionary[dict_keys[0]], dict_keys[1:])

print(get_nested_keys(enron, ('Mark',)))
print(get_nested_keys(enron, ('Mark','employed')))

打印:

['employed', 'salary']
['boogie']

答案 1 :(得分:0)

尝试使用此库addict https://github.com/mewwts/addict

如果这是你要求的懒惰方式,你可以写dic.a.b.c而不是dic["a"]["b"]["c"]