Skip to main content
 首页 » 编程设计

Python 3.6 对 Dict 对象的变量替换

2025年05月04日14lidabo

我有以下字典对象:

AUTH_LDAP_USER_FLAGS_BY_GROUP = { 
    "is_active": "cn=active,ou=groups,dc=example,dc=com", 
    "is_staff": "cn=staff,ou=groups,dc=example,dc=com", 
    "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com" 
} 

我想从变量中定义它的元素:

# Load environmental variables here 
hostname = os.environ['AUTH_LDAP_SERVER'] 
binduser = os.environ['AUTH_LDAP_BIND_USER'] 
bindgroup = os.environ['AUTH_LDAP_BIND_GROUP'] 
dc1 = os.environ['AUTH_LDAP_BIND_DC1'] 
dc2 = os.environ['AUTH_LDAP_BIND_DC2'] 
bindpassword = os.environ['AUTH_LDAP_PASSWORD'] 
 
AUTH_LDAP_USER_FLAGS_BY_GROUP = { 
    "is_active": "cn=active,{bindgroup},dc={dc1),dc={dc2}", 
    "is_staff": "cn=staff,{bindgroup},dc={dc1},dc={dc2}", 
    "is_superuser": "cn=administrators,{bindgroup},dc={dc1},dc={dc2}" 
} 

如何将变量插入到字典中?

请您参考如下方法:

您需要做的就是在要格式化的字符串前面添加一个f。关于 f-strings 的文档.

AUTH_LDAP_USER_FLAGS_BY_GROUP = { 
    "is_active": f"cn=active,{bindgroup},dc={dc1},dc={dc2}", 
    "is_staff": f"cn=staff,{bindgroup},dc={dc1},dc={dc2}", 
    "is_superuser": f"cn=administrators,{bindgroup},dc={dc1},dc={dc2}" 
} 

此外,我会使用 os.getenv以避免 KeyError 的。