如何在python中提取多级字典键/值 [英] how to extract multi level dictionary keys/values in python

查看:1184
本文介绍了如何在python中提取多级字典键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中有一个二级字典:

There is a two level dictionary in python:

例如此处:index[term][id] = n
id = 3时如何获取termn?

for instance here: index[term][id] = n
how to get the term and n when id = 3?

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

推荐答案

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

Iterate over the nested dict and create new dict to map the values in the desired format. You can create your custom function like:

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理解如下所示:

OR, simple dict comprehension will look like:

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

d存放词典的位置.

这篇关于如何在python中提取多级字典键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆