python - 反转字典的层次结构的有效方法?
问题描述
我有一本要反转的字典。- 类似于翻转图表上的轴。所以我开始:
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 结构中?
解决方案
您可以使用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
}
}
推荐阅读
- apache-spark - 如何在 Pyspark shell 中添加 numpy
- c# - 如何使用以十六进制为密钥的 openssl_decrypt?
- graph - Neo4j:如何为具有多个关系的每对节点返回单个路径
- sql - 如何从 BigQuery 中的累积成本中获取每小时滞后成本?
- python - 将 time.sleep 与 webdriver 一起使用
- python - Methodology to stop remote autostart celery servers on start up when need changes
- c++ - 在 for 循环外和 for 循环内初始化字符串有什么区别?
- node.js - adal-node 包中的代理设置
- vba - Excel VBA 代码 - 全局模块/子 OOP 友好?
- azure-devops - NuGetToolInstaller 任务是否应该需要 .Net 4.7.2 并且应该使用该任务添加 .Net framework 4.7.2 作为需求?