Kurt Peek Kurt Peek - 2 months ago 10
Python Question

DRY selection of a subset of a dictionary

Suppose I have a dictionary

config
which, among others, has the keys
username
and
password
. I'd like to create a new dictionary consisting only of the
username
and
password
key-value pairs from
config
. One way to do this is:

new_dictionary = {'username': config['username'], 'password': config['password']}


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

Answer

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

new_dictionary = {k: config[k] for k in ('username', 'password')}
Comments