首页 > 解决方案 > 反转字典的层次结构的有效方法?

问题描述

我有一本要反转的字典。- 类似于翻转图表上的轴。所以我开始:

dict_by_years = {
    2012: {}, 
    2013: {
        'US': 84,
        'CN': 394, 
        'JP': 171, 
        'TW': 39,
    }, 
    2014: {
        'US': 70, 
        'CN': 444, 
        'JP': 155, 
        'TW': 43,
    },   
    2015: { 
        'US': 76,
        'CN': 430, 
        'JP': 141,
        'TW': 39,
        'PH': 15,
    },
}

我想结束:

dict_by_country_codes = {
    'US': {
        2013: 84,
        2014: 70,
        2015: 76,
    },
    'CN': {
        2013: 394,
        2014: 444,
        2015: 430,
    },
    'JP': {
        2013: 171,
        2014: 155,
        2015: 141,
    },
    'TW': {
        2013: 39,
        2014: 43,
        2015: 39,
    },
    'PH': {
        2015: 15,
    }
}

当然,数据会不一致且不可预测。有没有更好的方法来实现这一点,而不是遍历每个层次结构并将值添加到新的 dict 结构中?

标签: pythondictionary

解决方案


您可以使用collections.defaultdict

from collections import defaultdict
d = defaultdict(dict)
for a, b in dict_by_years.items():
   for c, _d in b.items():
      d[c][a] = _d

import json
print(json.dumps(dict(d), indent=4))

输出:

{
"US": {
    "2013": 84,
    "2014": 70,
    "2015": 76
},
"CN": {
    "2013": 394,
    "2014": 444,
    "2015": 430
},
"JP": {
    "2013": 171,
    "2014": 155,
    "2015": 141
},
"TW": {
    "2013": 39,
    "2014": 43,
    "2015": 39
},
"PH": {
    "2015": 15
  }
}

推荐阅读