Merging two dic in python3 using Unpacking Generalisations in Python3.5
<p>There are two dictionaries as follow which I want to merge them, my point is to select those keys that I am interested in, for example I am interested in all the keys except county. Solution I 've used is using <code>del</code> function after creating your new dictionary, however I am sure there are more ways that are more efficient to my solution. How can I solve this problem without del function using <strong>UNPACKING ARGUMENT</strong>.</p>

<pre><code>    &gt;&gt;&gt; d1 =  {'avgUserperDay': '12', 'avgPurchaseperDay': '1', 'country': 'Japan'}
    &gt;&gt;&gt; d2 = {'tUser': 1, 'tPurchase': 0, 'country': 'Japan'}
    &gt;&gt;&gt; d ={**d1,**d2}
    &gt;&gt;&gt;{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12', 'country': 'Japan'}
    &gt;&gt;&gt; del d['country']
    &gt;&gt;&gt; d
    {'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}
</code></pre>

<p>AFTER DISCUSSION, </p>

<p>This command works with 3.5.1,</p>

<pre><code>&gt;&gt;&gt; {**{k:v for k, v in chain(d1.items(), d2.items()) if k != 'country'}}
{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}
</code></pre>

<blockquote>
  <p>How can I solve this problem without del function using UNPACKING ARGUMENT?</p>
</blockquote>

<p>Yes, you can. But you should not. Ideal way should be:</p>

<pre><code>d1.update(d2)   # values will be updated in d1 dict
del d1['country']
</code></pre>

<p>There no direct way to meet your conditions:</p>

<ul>
<li>create new <code>dict</code> using <em>argument unpacking</em></li>
<li>not using <code>del</code> to remove country.</li>
</ul>

<p>But there are work around if this is what you want. For example using <code>itertools.chain()</code> with <em>dict comprehension</em> as:</p>

<pre><code>{**{k:v for k, v in chain(d1.items(), d2.items()) if k != 'country'}}
</code></pre>

<p><em>Note:</em> For those curios about how <code>{**dict1, **dict2}</code> even works. It is new syntax supported since from python 3.5+, proposed in <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 448</a>. Check: <a href="https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations" rel="nofollow">What's New in Python 3.5</a> document.</p>

<p>Since, <strong><code>{**dict1, **dict2}</code> is only supported in Python 3.5+</strong>, for earlier version of Python, you can do (as mentioned by S. <a href="http://stackoverflow.com/a/39875454/2063361">De Melo</a>):</p>

<pre><code>d = dict(d1, **d2)
d.pop("country")
</code></pre>

<p>OR without using <code>**</code> as:</p>

<pre><code>{k, v for k, v in chain(d1.iteritems(), d2.iteritems()) if k != 'country'}
</code></pre>

python python-3.5 argument-unpacking