0

I have 2 lists of dictionaries:

I want to loop over each demand and each supply, if the value ('val') matches then I want to copy the dictionary line over into a new dictionary (Matches) and add Dname from the matched demand list, and remove it from the supply/demand list(or make the value in the original dictionary 0).

demand = [
{'id':1, 'Dname': 'A',  'val': 9},
{'id':2, 'Dname': 'B',  'val': 12},
{'id':3, 'Dname': 'C',  'val': 7},
 ];
 supply = [
 {'id':11, 'Sname': 's',  'val': 21},
 {'id':12, 'Sname': 't',  'val': 9},
  ];

I have tried this, but it formats both supply list and new list "Matches". So I cannot make the val =0 in the supply list and keep it to the original value in the new Matches list

Matches=[]
          for source in supply:
             for sink in demand:

          if source ['val'] == sink['val']:             #checking if there are any identical matches   
             Matches.append(source)                   #adding match (source) to matches list
            #Getting matches index to add sink to matches
            name_indexer = dict((p['Sname'], i) for i, p in enumerate(Matches))     
            index_no_matches=name_indexer.get(source['Sname']) 

            Matches[index_no_matches]['Dname'] = sink['Dname']  
            source['val']=0`

'''

Thanks!

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • The code will currently have syntax errors due to a missing `'` and due to inconsistent indentation. Please can you edit the question so that it shows the code exactly as run. – alani May 31 '20 at 10:17
  • `import copy` + `Matches.append(copy.deepcopy(source))` – Patrick Artner May 31 '20 at 10:17
  • with `Matches.append(source)` you append _the reference_ to your dict to `Matches`. references point to the same data. You need to copy it. See the dupe, lists work the same. – Patrick Artner May 31 '20 at 10:18

0 Answers0