How to add two dictionaries in python with same keys

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']],   ## 

Chủ Đề