在词典中存储多个响应

时间:2014-05-07 09:06:08

标签: python python-2.7

我有一个文件 main.txt

{
    "a": "2014T00+0000",
    "max": 6924,
    "maxi": 86924,
    "rP": 0,
    "rPS": 100,
    "rT": 372,
    "res": [
        {
            "aDV": 11,
            "aVs": 2,
            "acc": null,
            "as": null,
            "cs": [],
            "mP": [
                {
                    "len": 2,
                    "st": 5,
                    "txt": "adas"
                }
            ]
        },
        {
            "aDV": 112,
            "aVs": 23,
            "acc": null,
            "as": null,
            "cs": [],
            "mP": [
                {
                    "len": 22,
                    "st": 51,
                    "txt": "adasA"
                }
            ]
        }
    ],
    "sD": "2014-04-01T00:00:00.000+0000"
}

我想将每个响应存储在以“:”分隔的单独字典中。完整响应采用此("res"[{response 1},{response 2},......{response n}],)格式。个人响应格式与此({"a":b},)类似。上面的文件包含2个回复(res[{response1},{response2}],)。第一个响应需要存储在字典#1中,依此类推。可以有一个可以指向这些词典的列表。

任何帮助都会很好。感谢。

1 个答案:

答案 0 :(得分:1)

这看起来像json(编辑:看起来不像,它是有效的json格式化的)

import json

handler = open('main.txt', 'r')
data = json.loads(handler.read())

然后访问数据:

>>> len(data['res'])
2

>>> bb['res'][0]  # First response
{u'acc': None, u'aDV': 11, u'aVs': 2, u'as': None, u'mP': [{u'txt': u'adas', u'len': 2, u'st': 5}], u'cs': []}

>>> bb['res'][1]  # Second response
{u'acc': None, u'aDV': 112, u'aVs': 23, u'as': None, u'mP': [{u'txt': u'adasA', u'len': 22, u'st': 51}], u'cs': []}
相关问题