【问题标题】:how to extract multi level dictionary keys/values in python如何在python中提取多级字典键/值
【发布时间】:2016-11-17 14:25:32
【问题描述】:

python中有一个二级字典:

例如这里:index[term][id] = n
id = 3时如何获得termn

或者如果它以result[id] = [term, n]这样的形式返回就完美了

【问题讨论】:

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

标签: python dictionary key key-value


【解决方案1】:

遍历嵌套的 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

或者,简单的dict理解看起来像:

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

d 存放您的字典的位置。

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 2021-09-03
    • 1970-01-01
    • 2013-03-28
    • 2017-04-09
    • 2019-08-19
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多