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

如何在python中提取多级字典键/值,python,dictionary,key,key-value,Python,Dictionary,Key,Key Value,python中有一个两级字典: 例如这里:index[term][id]=n 当id=3时,如何获取术语和n 或者,如果它以类似result[id]=[term,n]的形式返回,则最好迭代嵌套的dict并创建新的dict,以所需格式映射值。您可以创建自定义函数,如: def get_tuple_from_value(my_dict): new_dict = {} for term, nested_dict in my_dict.items(): for id, n

python中有一个两级字典:

例如这里:
index[term][id]=n

id=3
时,如何获取
术语和
n


或者,如果它以类似
result[id]=[term,n]
的形式返回,则最好迭代嵌套的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
存放词典的位置。

ID是唯一的吗?你能提供实际字典的样子吗?是的,id是唯一的,索引实际上存储了文档集合中的单词(术语)。索引['和'][456]=7表示在documnet456中,'和'出现7次。您可以将字典反转为
index[documentId][word]=count