cari

Rumah  >  Soal Jawab  >  teks badan

python dict merge

Terdapat dua kamus a dan b Kedua-duanya mempunyai id yang sama 1. Penggabungan dicts
sangat serupa dengan hasil pelaksanaan dalam mysqlselect a.id,a.MUT,b.neighbor from a full join b on a.id = b.id

.
    a =  {
        "id": "1",
        "MUT": "1500",
    }
    b =  {
        "id": "1",
        "neighbor": [2]
    }
    # result = addfunction(a,b)
    result = {
        "id": "1",
        "MUT": "1500",
        "neighbor": [2]
    }

Bagaimana untuk melaksanakan?



Pertimbangkan komplikasi:

a =  [
    {
        "id": "1",
        "MUT": "1500",
    },
    {
        "id": "2",
        "MUT": "1500",
    }
]
b =  [
    {
        "id": "1",
        "neighbor": [2]
    },
     {
        "id": "3",
        "neighbor": [2]
    }
]
# result = addfunction(a,b)
result = [
    {
        "id": "1",
        "MUT": "1500",
        "neighbor": [2]
    },
     {
        "id": "2",
        "MUT": "1500",
    },
     {
        "id": "3",
        "neighbor": [2]
    }
]
迷茫迷茫2753 hari yang lalu919

membalas semua(2)saya akan balas

  • PHP中文网

    PHP中文网2017-06-14 10:55:21

    l_a = len(a)
    l_b = len(b)
    
    b_map = {}
    result = []
    for _ in range(l_b):
        i = b.pop()
        b_map[i['id']] = i
    
    for _ in range(l_a):
        i = a.pop()
        if i['id'] in b_map:
            i.update(b_map.pop(i['id']))
        result.append(i)
    
    result.extend(b_map.values())
    print(result)
    
    [{'MUT': '1500', 'id': '2'}, {'MUT': '1500', 'id': '1', 'neighbor': [2]}, {'id': '3', 'neighbor': [2]}]
    

    balas
    0
  • 某草草

    某草草2017-06-14 10:55:21

    from collections import defaultdict
    
    def combineListDict(l1,l2,joinKeys = ["id"]):
        d = defaultdict(dict)
        for l in (l1, l2):
            for elem in l:
                if len(joinKeys) == 1:
                    joinKeysStr = elem[joinKeys[0]]
                else:
                    joinKeysStr = reduce((lambda x, y: str(elem[x]) + str(elem[y])),joinKeys)
                d[joinKeysStr].update(elem)
        return d.values()
    

    Oleh kerana gabungan dengan syarat mungkin mempunyai berbilang nilai, saya menemui kod pada tindanan dan menukarnya.

    balas
    0
  • Batalbalas