通过对行进行分组,从输入矩阵创建json文件

时间:2015-03-25 00:10:36

标签: python json dictionary transpose

给定下面的矩阵,我想创建和json输出,它将迭代矩阵行并附加项目(col 1),如果组(col2)重复:

  matrix = [ 
        ['JAN', '1', 'abc'], 
        ['FEB', '7', 'xyz'], 
        ['FEB', '4', 'abc'], 
        ['MAR', '3', 'xyz'], 
        ['DEC','12', 'xyz']
      ]

如何创建输出/ JSON文件:

{
     "month": ["JAN","FEB","FEB","MAR","DEC"],
     "items": [
        { "group":"abc",
         "data":[1,4]
        },
        { "group":"xyz",
         "data":[7,3,12]
        }
      ]
    }

我已经尝试了转置矩阵/列并构建了一个字典,我在for循环中追加项目,但我遗漏了一些东西而且它变得混乱了。这应该是一个简单的方法。

2 个答案:

答案 0 :(得分:6)

这个程序:

from itertools import groupby
import json
matrix = [
    ['JAN',  '1', 'abc'],
    ['FEB',  '7', 'xyz'],
    ['FEB',  '4', 'abc'],
    ['MAR',  '3', 'xyz'],
    ['DEC', '12', 'xyz']
]
months = [x[0] for x in matrix]
items = [[x[2], int(x[1])] for x in matrix]
items = sorted(items, key=lambda x: x[0])
items = groupby(items, lambda x: x[0])
items = [{"group": k, "data": [x[1] for x in g]} for k, g in items]
result = {
    "month": months,
    "items": items
}
print (json.dumps(result, sort_keys=True, indent=4, separators=(',', ': ')))

生成此输出:

{
    "items": [
        {
            "data": [
                1,
                4
            ],
            "group": "abc"
        },
        {
            "data": [
                7,
                3,
                12
            ],
            "group": "xyz"
        }
    ],
    "month": [
        "JAN",
        "FEB",
        "FEB",
        "MAR",
        "DEC"
    ]
}

答案 1 :(得分:-1)

最好使用json模块,但你可以在演员表后标准文件写作:

with open('data.json', 'w') as data:
    data.write(str(my_dict))