How to merge multiple dicts with same key?

前端 未结 14 2637
别跟我提以往
别跟我提以往 2020-11-22 13:12

I have multiple dicts/key-value pairs like this:

d1 = {key1: x1, key2: y1}  
d2 = {key1: x2, key2: y2}  

I want the result to be a new di

14条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 13:57

    To supplement the two-list solutions, here is a solution for processing a single list.

    A sample list (NetworkX-related; manually formatted here for readability):

    ec_num_list = [((src, tgt), ec_num['ec_num']) for src, tgt, ec_num in G.edges(data=True)]
    
    print('\nec_num_list:\n{}'.format(ec_num_list))
    ec_num_list:
    [((82, 433), '1.1.1.1'),
      ((82, 433), '1.1.1.2'),
      ((22, 182), '1.1.1.27'),
      ((22, 3785), '1.2.4.1'),
      ((22, 36), '6.4.1.1'),
      ((145, 36), '1.1.1.37'),
      ((36, 154), '2.3.3.1'),
      ((36, 154), '2.3.3.8'),
      ((36, 72), '4.1.1.32'),
      ...] 
    

    Note the duplicate values for the same edges (defined by the tuples). To collate those "values" to their corresponding "keys":

    from collections import defaultdict
    ec_num_collection = defaultdict(list)
    for k, v in ec_num_list:
        ec_num_collection[k].append(v)
    
    print('\nec_num_collection:\n{}'.format(ec_num_collection.items()))
    ec_num_collection:
    [((82, 433), ['1.1.1.1', '1.1.1.2']),   ## << grouped "values"
    ((22, 182), ['1.1.1.27']),
    ((22, 3785), ['1.2.4.1']),
    ((22, 36), ['6.4.1.1']),
    ((145, 36), ['1.1.1.37']),
    ((36, 154), ['2.3.3.1', '2.3.3.8']),    ## << grouped "values"
    ((36, 72), ['4.1.1.32']),
    ...] 
    

    If needed, convert that list to dict:

    ec_num_collection_dict = {k:v for k, v in zip(ec_num_collection, ec_num_collection)}
    
    print('\nec_num_collection_dict:\n{}'.format(dict(ec_num_collection)))
      ec_num_collection_dict:
      {(82, 433): ['1.1.1.1', '1.1.1.2'],
      (22, 182): ['1.1.1.27'],
      (22, 3785): ['1.2.4.1'],
      (22, 36): ['6.4.1.1'],
      (145, 36): ['1.1.1.37'],
      (36, 154): ['2.3.3.1', '2.3.3.8'],
      (36, 72): ['4.1.1.32'],
      ...}
    

    References

    • [this thread] How to merge multiple dicts with same key?
    • [Python docs] https://docs.python.org/3.7/library/collections.html#collections.defaultdict

提交回复
热议问题