DRY selection of a subset of a dictionary
<p>Suppose I have a dictionary <code>config</code> which, among others, has the keys <code>username</code> and <code>password</code>. I'd like to create a new dictionary consisting only of the <code>username</code> and <code>password</code> key-value pairs from <code>config</code>. One way to do this is:</p>

<pre><code>new_dictionary = {'username': config['username'], 'password': config['password']}
</code></pre>

<p>This seems a bit verbose to me, as it contains repetitions of the words <code>username</code> and <code>password</code>. Is there a more succinct way to do this?</p>

<p>You can just create <code>tuple</code> or <code>list</code> that stores names of fields that you want to be copied and iterate through every element</p>

<pre><code>new_dictionary = {k: config[k] for k in ('username', 'password')}
</code></pre>

python dictionary