如何在Python中切换字典词典的嵌套结构 [英] How to switch the nesting structure of a dictionary of dictionaries in Python

查看:64
本文介绍了如何在Python中切换字典词典的嵌套结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下字典:

dict_a = {'a': {'x': 0, 'y': 1, 'z': 2},
          'b': {'x': 3, 'y': 4, 'z': 5}}

将字典结构切换为以下内容的最佳方法是什么

What is the best way to switch the structure of the dictionary to:

dict_b = {'x': {'a': 0, 'b': 3},
          'y': {'a': 1, 'b': 4},
          'z': {'a': 2, 'b': 5}}

推荐答案

使用默认字典

鉴于字典总是深两级,您可以使用 defaultdict :

from collections import defaultdict

dict_b = defaultdict(dict)

for k,v in dict_a.items():
    for k2,v2 in v.items():
        dict_b[k2][k] = v2

哪个给:

>>> dict_b
defaultdict(<class 'dict'>, {'x': {'a': 0, 'b': 3}, 'z': {'a': 2, 'b': 5}, 'y': {'a': 1, 'b': 4}})
>>> dict(dict_b)
{'x': {'a': 0, 'b': 3}, 'z': {'a': 2, 'b': 5}, 'y': {'a': 1, 'b': 4}}

defaultdict dict 的子类,您可以使用 dict_b = dict(dict_b)(如第二个查询所示).

defaultdict is a subclass of dict, you can turn the result again in a vanilla dict with dict_b = dict(dict_b) (as is demonstrated in the second query).

您还可以为此使用 pandas :

from pandas import DataFrame

dict_b = DataFrame(dict_a).transpose().to_dict()

这给出了:

>>> DataFrame(dict_a).transpose().to_dict()
{'y': {'a': 1, 'b': 4}, 'x': {'a': 0, 'b': 3}, 'z': {'a': 2, 'b': 5}}

这篇关于如何在Python中切换字典词典的嵌套结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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