如何在python中提取多级字典键/值

时间:2016-11-17 14:25:32

标签: python dictionary key key-value

python中有一个两级字典:

例如:index[term][id] = n
如何在term

时获取nid = 3

如果它以result[id] = [term, n]

之类的形式返回,那将是完美的

1 个答案:

答案 0 :(得分:3)

迭代嵌套的dict并创建新的dict以便以所需的格式映射值。您可以创建自定义函数,如:

def get_tuple_from_value(my_dict):
    new_dict = {}
    for term, nested_dict in my_dict.items():
        for id, n in nested_dict.items():
            new_dict[id] = [term, n]
    return new_dict

或者,简单的字典理解将如下所示:

{i: [t, n] for t, nd in d.items() for i, n in nd.items()}

d在哪里拿着你的字典。

相关问题