返回具有多个方差的单个值

时间:2019-06-27 15:31:58

标签: python

我有一个具有以下值的表:

Id   Name                  Description
1   (Red) Mazda             Nice
2    Ferrari                Super Nice
3   (Black) Mazda           Nice
4    Mazda                  Nice

我这样退还他们:

for row in all_cars:
     rows_as_dict = {
         "id": row.id,
         "car": {
             "name": row.name,
             "description": row.description,
         }
     }
     all_cars.append(rows_as_dict)

我如何做到这一点,以便我可以以某种方式将其退回,如果汽车有差异,它应该看起来像这样:

res = [{
     "id" : "4",
     "cars" : {
            "name": "Mazda",
            "description": "Nice",
            "variance": [
                "Red",
                "Black"
      ]},{
     "id" : "2",
     "cars" : {
            "name": "Ferrari",
            "description": "Super Nice",
            "variance": [
            ]
     }]

1 个答案:

答案 0 :(得分:0)

data = '''
Id   Name                  Description
1   (Red) Mazda             Nice
2    Ferrari                Super Nice
3   (Black) Mazda           Nice
4    Mazda                  Nice'''

import re
from collections import defaultdict
import json

tbl = [*re.findall(r'^(\d+)\s+(.*?)\s{2,}(.*)$', data, flags=re.M)]

variances = defaultdict(list)
out = {}
for (id_, name, desc) in tbl:
    g = re.match(r'^(?:\(([^)]+)\))?\s*(.*)', name).groups()
    if g[0]:
        variances[g[1]].append(g[0])
    out[g[1]] = {
         "id": id_,
         "car": {
             "name": g[1],
             "description": desc,
         }
     }

for k, v in out.items():
    out[k]['variance'] = variances[k]

print(json.dumps([*out.values()], indent=4))

打印:

[
    {
        "id": "4",
        "car": {
            "name": "Mazda",
            "description": "Nice"
        },
        "variance": [
            "Red",
            "Black"
        ]
    },
    {
        "id": "2",
        "car": {
            "name": "Ferrari",
            "description": "Super Nice"
        },
        "variance": []
    }
]