在python中导入2个字典列表和嵌套键/值对

时间:2019-06-16 05:06:59

标签: python json

我有2个json,它们是字典列表,我想用它们在python中创建第3个json。

第一个json是 last_names.json

[{
    "firstnameID": "1",
    "name": "John",
    "lastnameID": "1"
}, {
    "firstnameID": "2",
    "name": "Jane",
    "lastnameID": "1"
}, {
    "firstnameID": "3",
    "name": "Bob",
    "lastnameID": "2"
}, {
    "firstnameID": "4",
    "name": "Mary",
    "lastnameID": "2"
}]

第二个json是 first_names.json

[{
    "lastnameID": "1",
    "name": "Doe",
    "first names": [{
        "firstnameID": "1",
        "name": "John"
    }, {
        "firstnameID": "2",
        "name": "Jane"
    }]
}, {
    "lastnameID": "2",
    "name": "Smith",
    "first names": [{
        "firstnameID": "3",
        "name": "Bob"
    }, {
        "firstnameID": "4",
        "name": "Mary"
    }]
}]

我希望我的输出是这个 output.json

import json

finaljson = []
with open('first_names.json', 'r') as f:
    firstnames = json.load(f)
with open('last_names.json', 'r') as f:
    lastnames = json.load(f)
for i in range (0, len (lastnames)):
    firstnamelist = []
    lastnameID = lastnames[i]['lastnameID']
    lastname = lastnames[i]['name']
    for i in range (0, len (firstnames))
        if firstnames[i]['lastnameID'] == lastnameID:
            firstname = firstnames[i]['name']
            firstnameID = firstnames[i]['firstnameID']
            firstnamelist.append("firstnameID":firstnameID,"name":firstname)
    finaljson.append({"lastnameID":lastnameID,"name":lastname,"firstnames":firstnamelist})

如何在python 3上执行此操作?

我在下面尝试过,但是必须有比这更好的方法

:-1: Capabilities for Pitch Perfect may not function correctly because its entitlements use a placeholder team ID. To resolve this, select a development team in the build settings editor. (in target 'Pitch Perfect')

1 个答案:

答案 0 :(得分:1)

词典内

print('static unsigned int facMod10p7[] = {\n    0,')
val = 1
mult = 2
for i in range(100000):
    print('    {},'.format(val) % 1000000007)
    val *= mult
    mult += 1
print(');')

请查看以下结果:

for first_ in first:
    first_['first names'] = [{x:y for x, y in second_.items() if x == 'firstnameID' or x == 'name'} 
                             for second_ in second if second_['lastnameID'] == first_['lastnameID']]

print (first)