转换python字典

时间:2019-05-24 13:20:44

标签: python dictionary

我想转换一个python字典。从这里:

{
    "y2019": {
        "Jan": 1,
        "Feb": 8
    },
    "y2018": {
        "Jan": 16,
        "Feb": 3
    }
}

对此:

{
    "Jan": {
        "y2019": 1,
        "y2018": 16
    },
    "Feb": {
        "y2019": 8,
        "y2018": 3
    }
}

键不固定。有类似的收藏计数吗?

3 个答案:

答案 0 :(得分:0)

代码:

tmp = {
        "y2019": {
            "Jan": 1,
            "Feb": 8
        },
        "y2018": {
            "Jan": 16,
            "Feb": 3
        }
    }

rev_tmp = {}

for k1, v1 in tmp.items():
    for k2, v2 in v1.items():
        t = rev_tmp.get(k2, None)
        if not t:
            t = {}
            rev_tmp[k2] = t
        t.update({k1: v2})

输出:

{'Jan': {'y2019': 1, 'y2018': 16}, 'Feb': {'y2019': 8, 'y2018': 3}}

答案 1 :(得分:0)

如果您想使用集合,则可以使用default dictionaries

from collections import defaultdict

start = {
    "y2019": {
        "Jan": 1,
        "Feb": 8
    },
    "y2018": {
        "Jan": 16,
        "Feb": 3
    }
}

new_dict = defaultdict(dict)
for year,value in start.items():
    for k,v in value.items():
        new_dict[k][year] = v

print(new_dict)

输出

defaultdict(<class 'dict'>, {
  'Jan': {
    'y2019': 1, 
    'y2018': 16
  }, 'Feb':{
       'y2019': 8, 
       'y2018': 3
    }
 })

答案 2 :(得分:0)

这是解决此问题的一种方法:

a = {
    "y2019": {
        "Jan": 1,
        "Feb": 8
    },
    "y2018": {
        "Jan": 16,
        "Feb": 3
    }
}

new_a = {}

for i in a.keys():
    for j in a[i].keys():
        new_a[j] = {}
        for k in a.keys():
            new_a[j][k] = a[k][j]

print(new_a)

输出:

{'Jan': {'y2019': 1, 'y2018': 16}, 'Feb': {'y2019': 8, 'y2018': 3}}