繁体   English   中英

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

[英]Expand a list of dictionaries into a readable format

因为我是python的新手,所以可能缺少我的描述/标题,但是作为示例,我目前将如下数据存储在变量bunnies

[{''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 ':'牛排','儿童':108,'工作':'厨师','等':'等','等':'等'},{'兔子洞':{'洞数':3,' family':'roger','status':'elite'},'food':'steak','children':108,'job':'chef','etc':'etc','etc': '等等'}]

我的目标是将其分解为如下所示的可读格式:

{
'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)

这给了我每个兔子洞列表的新行...

所以我尝试了这个:

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)

我还没有对这个错误进行过多的研究,但是我仍然觉得自己走错了方向。

谁能帮助我指出正确的方向?

您可以使用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"
        }
    }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM