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 could store the username/password pair in a sub dictionary (called credential)</p>

<pre><code>config = { 'param1': 'value1', 'credential': { 'username': 'myname', 'password': 'pa22w0rd' } }
new-dictionary = config['credential']
</code></pre>

<p>You could create a credential class and pass that object around instead of a dictionary.</p>

python dictionary