无法匹配python中字典中的键

2024-09-23 22:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我把下面这句话指定为

dict1 = {('Q6', 'pic'): 'yes'}

我正在尝试匹配dict1中的键Q6,pic。我使用以下代码

dict1Index = 6
key = 'Q' + str(dict1Index)
dictPicKey = key + "," + "pic"
if dictPicKey in dict1 : 

print "*****"

它与输出不匹配


Tags: key代码inifyesprintstrpic
2条回答

您只是在创建一个带有逗号的字符串。你要找的钥匙是薄纱。试试这个:

dict1Index = 6 
key = 'Q' + str(dict1Index)
dictPicKey = (key, "pic") 
if dictPicKey in dict1 : 
    print "*****"

请看以下内容:

>>> type(('Q6', 'pic'))
<type 'tuple'>
>>> type('Q6,pic')
<type 'str'>
>>> ('Q6', 'pic') == 'Q6,pic'
False

键是一个元组,元组的元素是"Q6""pic",而字符串对象"Q6,pic"not。你知道吗

您应该从这些字符串创建元组,然后检查字典中是否存在元组。你知道吗

相关问题 更多 >