在python中重新排列嵌套字典的级别 [英] Rearranging levels of a nested dictionary in python

查看:83
本文介绍了在python中重新排列嵌套字典的级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个图书馆可以帮助我完成重新排列嵌套字典级别的任务

Is there a library that would help me achieve the task to rearrange the levels of a nested dictionary

例如:来自此:

{1:{"A":"i","B":"ii","C":"i"},2:{"B":"i","C":"ii"},3:{"A":"iii"}}

为此:

{"A":{1:"i",3:"iii"},"B":{1:"ii",2:"i"},"C":{1:"i",2:"ii"}}

换成3层词典的前两个层。因此,我们有一个映射到1和3的映射,而不是1映射到A的映射和3映射到A的映射。

ie first two levels on a 3 levelled dictionary swapped. So instead of 1 mapping to A and 3 mapping to A, we have A mapping to 1 and 3.

该解决方案应适用于任意深度并从一个

The solution should be practical for an arbitrary depth and move from one level to any other within.

推荐答案

>>> d = {1:{"A":"i","B":"ii","C":"i"},2:{"B":"i","C":"ii"},3:{"A":"iii"}}
>>> keys = ['A','B','C']
>>> e = {key:{k:d[k][key] for k in d if key in d[k]} for key in keys}
>>> e
{'C': {1: 'i', 2: 'ii'}, 'B': {1: 'ii', 2: 'i'}, 'A': {1: 'i', 3: 'iii'}}

感谢上帝对字典的理解

这篇关于在python中重新排列嵌套字典的级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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