Combining two dictionaries into one with the same keys?

前端 未结 7 1772
眼角桃花
眼角桃花 2020-12-06 03:35

I\'ve looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{\'A\': 25 ,          


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 04:09

    Use pydash

    from pydash import merge_with
    cbk = lambda obj_val, src_val: obj_val + src_val
    obj1 = {'a': [1], 'b': [2]}
    obj2 = {'a': [3], 'b': [4]}
    res = merge_with(obj1, obj2, cbk)
    print(res)
    

    Result:

    {'a': [1, 3], 'b': [2, 4]}
    

    you can also use dictlib

    import dictlib
    obj1 = {'a': [1], 'b': [2]}
    obj2 = {'a': [3], 'b': [4],"c":[3]}
    c = dictlib.union_setadd(obj1, obj2)
    print(c)    
    {'a': [1, 3], 'b': [2, 4], 'c': [3]}
    

提交回复
热议问题