从json文件的一部分创建字典

时间:2018-04-25 19:42:29

标签: python json python-3.x

我正在尝试创建两个单独的词典,一个只保存车辆信息,另一个只保存车票信息。

{
"cars": [{
        "model": "toyota",
        "plate": "A11",
        "tickets": [{
                "amount": 50,
                "type": "A1"
            },
            {
                "amount": 34,
                "type": "A2"
            }
        ]
    },
    {
        "model": "mazda",
        "plate": "A11",
        "tickets": [{
                "amount": 50,
                "type": "A1"
            },
            {
                "amount": 34,
                "type": "A2"
            }
        ]
    }
 ]
}


import json

with open('jsonfile', 'r') as data:
cars_dict = json.load(data)

然后循环生成两个单独的dict s。我创建了循环,但仍未正确实现结果。

所需的输出将是:

dict_cars = [{'Model':'Toyota', 'Plate':'A11'},
             {'Model':'Mazda', 'Plate':'A13'}]

dict_cars = [{'Model':'Toyota', 'Plate':'A11', Tickets[......]},
             {'Model':'Mazda', 'Plate':'A13'}, Tickets[......]]

dict_tickets = [{'amount:50',type:'A1'},
                {'amount:34',type:'A2'},
                {'amount:50',type:'A1'},
                {'amount:34',type:'A2'}]

2 个答案:

答案 0 :(得分:0)

只需遍历json对象并解析值:

d = {
"dict_cars": [{
        "model": "toyota",
        "plate": "A11",
        "tickets": [{
                "amount": 50,
                "type": "A1"
            },
            {
                "amount": 34,
                "type": "A2"
            }
        ]
    },
    {
        "model": "mazda",
        "plate": "A11",
        "tickets": [{
                "amount": 50,
                "type": "A1"
            },
            {
                "amount": 34,
                "type": "A2"
            }
        ]
    }
]
}

dict_cars=[]
dict_tickets=[]
for i,j in d.items():
    for k in j:
        dict_cars.append({k.get('model',''):k.get("plate","")})
        for t in k.get('tickets',""):
            dict_tickets.append(t)

print("dict_cars = ",dict_cars)
print("dict_tickets = ",dict_tickets)

dict_cars = [{'toyota': 'A11'}, {'mazda': 'A11'}] dict_tickets = [{'amount': 50, 'type': 'A1'}, {'amount': 34, 'type': 'A2'}, {'amount': 50, 'type': 'A1'}, {'amount': 34, 'type': 'A2'}]

答案 1 :(得分:0)

import json

with open('file.json', 'r') as data:
    text = data.read()

cars = json.loads(text)['cars']
tickets = []

for arr in cars:
    for item in arr['tickets']:
        tickets.append(item)

    del arr['tickets']

print(tickets)
print(cars)

输出:

[{u'amount': 50, u'type': u'A1'}, {u'amount': 34, u'type': u'A2'}, {u'amount': 50, u'type': u'A1'}, {u'amount': 34, u'type': u'A2'}]
[{u'plate': u'A11', u'model': u'toyota'}, {u'plate': u'A11', u'model': u'mazda'}]