Python 字典子集的干选择

Python 字典子集的干选择,python,dictionary,Python,Dictionary,假设我有一个字典config,其中包括username和password。我想从config创建一个新字典,它只包含username和password键值对。一种方法是: new_dictionary = {'username': config['username'], 'password': config['password']} 这对我来说似乎有点冗长,因为它包含重复的单词username和password。有更简洁的方法吗?您只需创建元组或列表,其中存储要复制的字段名称并遍历每个元素 n

假设我有一个字典
config
,其中包括
username
password
。我想从
config
创建一个新字典,它只包含
username
password
键值对。一种方法是:

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

这对我来说似乎有点冗长,因为它包含重复的单词
username
password
。有更简洁的方法吗?

您只需创建
元组
列表
,其中存储要复制的字段名称并遍历每个元素

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

您可以将用户名/密码对存储在子字典(称为凭据)中

您可以创建一个凭证类并传递该对象,而不是一个字典。

dict((k,config[k])表示k in('username','password'))
config = { 'param1': 'value1', 'credential': { 'username': 'myname', 'password': 'pa22w0rd' } }
new-dictionary = config['credential']