如果它的键可以有多个值,如何从dict中获取值 [英] How to get value from dict if its key can have several values
问题描述
我有一个字典,其凭据如下所示:
I have a dict with credentials like the following:
secret = {"password": "jdksal",
"user": "fjdklas",
"schema": "jfdaskl"}
我想为密码,用户和架构创建一个变量.但是,秘密dict的每个键都可以具有其他值,因此我将列出命名元素的可能方法,如下所示:
I want to create a variable for password, user and schema. However, the secret dict can have other values for each key, so that I would have a list of possibles ways of naming the elements, like the following:
pass_words = ['password', 'pass', 'contraseña']
因此,当字典中存在 pass_words
列表中的任何键时,将创建可变密码.字典中仅会出现pass_words中的一个单词.与用户,架构等相同.到目前为止,我有以下代码:
Thus, the variable password would be created when any key of the list pass_words
exists in the dictionary. Only one word from pass_words would be present in the dict. Same with user, schema etc. So far I have this code:
for word in pass_words:
if word in secret:
password = secret[word]
user_words = ['user', 'username', 'login', 'name']
for word in user_words:
if word in secret:
user = secret[word]
它可以工作,但是非常冗长.有没有那么冗长的方法呢?谢谢
It works, but its very verbose. Is there any less verbose way to do it? Thanks
推荐答案
如您所写,如果 pass_word之间有多个重叠,则
和 password
将获得最后一个匹配项 secret
.我不知道那是你的意图.
As you have written it, password
will get the last match if there is more than one overlap between pass_word
and secret
. I don't know is that is your intent.
如果只有一个重叠,则可以使用set操作:
You could use set operations if there is only one overlap:
>>> secret.keys() & pass_words
{'password'}
>>> secret.keys() & user_words
{'user'}
然后获取与该键关联的值:
Then to get the value associated with that key:
>>> secret[(secret.keys() & pass_words).pop()]
jdksal
>>> secret[(secret.keys() & user_words).pop()]
fjdklas
对于没有字典集合视图的旧Python,只需对每个集合应用 set
即可得到相同的结果:
For older Pythons that don't have dict set views, just apply set
to each for the same result:
>>> set(secret.keys()) & set(user_words)
{'user'}
使用Python 3.6+,您可以执行以下操作:
With Python 3.6+, you can do:
password, user={k:v for k,v in secret.items() if k in pass_words+user_words}.values()
这篇关于如果它的键可以有多个值,如何从dict中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!