将字典列表展开为可读格式

时间:2015-11-07 11:46:16

标签: python python-2.7

我的描述/标题可能缺乏,因为我是python的新手,但是作为一个例子,我目前在变量bunnies中存储了如下数据:

  

[{' rabbithole':{' holenumber':1,' family':' roger',' status&# 39;:' elite'},   '食物':'牛排','孩子':'''':'厨师','等等':'等','等':   '},{' rabbithole':{' holenumber':2,' family':' roger', '状态&#39 ;:   ' elite'},' food&#39 ;:'牛排','孩子':108,'工作':&# 39;厨师','等':'等',   '等':'},{' rabbithole':{' holenumber':3,' family': '罗杰&#39 ;,   '状态':'精英'},'食物':'牛排','儿童':108,&# 39;工作':'厨师',   '等等'等等'等等':'等'}]

我的目标是将其分解为可读格式:

{
'rabbithole': {
    'holenumber': 1,
    'family': 'roger', 
    'status': 'elite'
}, 
'food': 'steak', 
'children': 108, 
'job': 'chef', 
'etc': 'etc', 
'etc': 'etc'
}

...

到目前为止我所拥有的是......

def virt(list):
    for i in list:
        print i
        print "\n"

virt(bunnies)

给了我每个rabbithole列表的新行...

所以我尝试了这个:

import re
def virt(list)
    for i in list:
        match = re.search( r'{|.*: {.*},|.*:.*,|}',i, re.I)
        print i.replace(match,match+"\n")

virt(bunnies)

不幸的是,除了从re库中抛出错误之外,它没有做任何事情。

File "/usr/lib64/python2.7/re.py", line 146, in search
    return _compile(pattern, flags).search(string)

我还没有对这个错误看得太多,但无论如何我感觉我的方向错了。

任何人都可以帮我指出正确的方向吗?

1 个答案:

答案 0 :(得分:1)

您可以使用json Python模块:

import json

print json.dumps(your_data, sort_keys=True, indent=4, separators=(',', ': '))

示例:

a=json.dumps([{'rabbithole': {'holenumber': 1, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}, {'rabbithole': {'holenumber': 2, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}, {'rabbithole': {'holenumber': 3, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}], sort_keys=True, indent=4, separators=(',', ': '))
>>> print a
[
    {
        "children": 108,
        "etc": "etc",
        "food": "steak",
        "job": "chef",
        "rabbithole": {
            "family": "roger",
            "holenumber": 1,
            "status": "elite"
        }
    },
    {
        "children": 108,
        "etc": "etc",
        "food": "steak",
        "job": "chef",
        "rabbithole": {
            "family": "roger",
            "holenumber": 2,
            "status": "elite"
        }
    },
    {
        "children": 108,
        "etc": "etc",
        "food": "steak",
        "job": "chef",
        "rabbithole": {
            "family": "roger",
            "holenumber": 3,
            "status": "elite"
        }
    }
]