title: Merge two list of dictionaries based on a condition
body: <p>I have two lists of dictionaries, and I need to merge them when ever <code>USA</code> and <code>GOOG</code> are the same.</p>
  
  <pre><code>list1 = 
  [{'USA': 'Eastern', 
    'GOOG': '2019', 
    'Up': {'Upfront': 45}, 
    'Right': {'Upfront': 12}}, 
  
   {'USA': 'Western', 
    'GOOG': '2019', 
    'Up': {'Upfront': 10}, 
    'Right': {'Upfront': 15}}]
  
  list2=
  [{'USA': 'Western', 
    'GOOG': '2019', 
    'Down': {'Downback': 35}, 
    'Right': {'Downback': 25}}, 
  
   {'USA': 'Eastern', 
    'GOOG': '2018', 
    'Down': {'Downback': 15}, 
    'Right': {'Downback': 55}}]
  </code></pre>
  
  <p>Since <code>USA</code> and <code>GOOG</code> had same values for 2nd element in <code>list1</code> and 1st element in <code>list2</code>, so they should be merged. The result expected is as follows - </p>
  
  <pre><code>Result = 
  [{'USA': 'Eastern', 
    'GOOG': '2019', 
    'Up': {'Upfront': 45}, 
    'Right': {'Upfront': 12}}, 
  
   {'USA': 'Western', 
    'GOOG': '2019', 
    'Up': {'Upfront': 10}, 
    'Down': {'Downback': 35}, 
    'Right': {'Upfront': 15, 'Downback': 25}},
  
   {'USA': 'Eastern', 
    'GOOG': '2018', 
    'Down': {'Downback': 15}, 
    'Right': {'Downback': 55}}]
  </code></pre>
  
  <p>How can we write a generic code for this. I tried using <a href="https://docs.python.org/2/library/collections.html" rel="nofollow noreferrer">defaultdict</a>, but did not know how to concatenate an arbitrary number of rest of dictionaries.</p>
  
  <p>My attempt:</p>
  
  <pre><code>from collections import defaultdict
  dics = list1+list2
  
  for dic in dics:
      for key, val in dic.items():
          dd[key].append(val)            
  
  for dic in dics:
      for key, val in dic.items(): 
          dd[key].append(val)
  </code></pre>