Operations with multiple dicts
<p>The main questions is how do I have to iterate / indicate correctly to work with two dicts?
I have given two dicts <code>(d1, d2)</code> which I have to compare. If the key i is the same in both, an operation is followed due to a given function. The result goes into another dict (<code>dict1</code>). If either <code>d1 or d2</code> contains the key i, the value goes in to <code>dict2</code>. The return is a <code>tup = (dict1, dict2)</code>. Here is an example.</p>

<pre><code>If f(a, b) returns a + b
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
then dict_interdiff(d1, d2) returns ({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})
</code></pre>

<p>I am struggling with the correct way to properly indicate the two dicts d1 and d2. Here is my code:</p>

<pre><code>def h(a, b):
    return a &gt; b    

d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
d1 = {1:30, 2:20, 3:30, 5:80}

def dict_interdiff(d1, d2):
    dict1 = {}
    dict2 = {}
    for i in d1:
        if i in d1 #and d2:
            dict1[i] = h(d1[i], d2[i])
        else:
            dict[i] = d1[i] #or d2[i]      
    tup = (dict1, dict2)
    return tup
</code></pre>

<p>Do I have to loop over d1 and d2 (<code>for i in d1 and d2:</code>)? It seems like I have to somehow integrate both given dicts to make the for loop work. </p>

<p>Thanks for any hints!</p>

<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain</code></a> to get an iterable of all keys in your dicts.</p>

<pre><code>from itertools import chain

def h(a, b):
    return a &gt; b

d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
d1 = {1:30, 2:20, 3:30, 5:80}

def dict_interdiff(d1, d2):
    dict1 = {}
    dict2 = {}
    for key in set(chain(d1, d2)):
        if key in d1 and key in d2:
            dict1[key] = h(d1[key], d2[key])
        else:
            dict2[key] = d1.get(key) or d2.get(key)
    return dict1, dict2
</code></pre>

python dictionary iteration