python quickest way to merge dictionaries based on key match

前端 未结 3 1873
余生分开走
余生分开走 2021-01-20 16:22

I have 2 lists of dictionaries. List A is 34,000 long, list B is 650,000 long. I am essentially inserting all the List B dicts into the List A dicts based on a key match.

3条回答
  •  孤城傲影
    2021-01-20 16:42

    I'd convert ListA and ListB into dictionaries instead, dictionaries with ID as the key. Then it is a simple matter to append data using python's quick dictionary lookups:

    from collections import defaultdict
    
    class thingdict(dict):
        def __init__(self, *args, **kwargs):
            things = []
            super(thingdict,self).__init__(*args, things=things, **kwargs)
    
    A = defaultdict(thingdict)
    A[1] = defaultdict(list)
    A[2] = defaultdict(list, things=[6])  # with some dummy data
    A[3] = defaultdict(list, things=[7])
    
    B = {1: 5, 2: 6, 3: 7, 4: 8, 5: 9}
    
    for k, v in B.items():
        # print k,v
        A[k]['things'].append(v)
    
    print A
    print B
    

    This returns:

    defaultdict(, {
        1: defaultdict(, {'things': [5]}),
        2: defaultdict(, {'things': [6, 6]}),
        3: defaultdict(, {'things': [7, 7]}),
        4: {'things': [8]},
        5: {'things': [9]}
    })
    {1: 5, 2: 6, 3: 7, 4: 8, 5: 9}
    

提交回复
热议问题