问题是每次通过循环时,您都会设置mykey = 'AAA'
. 因此,除非str
碰巧是最后一个值,否则您将用错误的值覆盖正确的答案。
让我们添加更多打印以更好地查看:
def value_for_value(d, str):
for key, value in d.iteritems():
mykey = 'AAA'
if value == str:
mykey = key
print key,value,type(value),str,type(str),mykey
return mykey
>>> value_for_value(Comp, 99)
Blue 101 <type 'int'> 99 <type 'int'> AAA
Ivory 103 <type 'int'> 99 <type 'int'> AAA
Black 99 <type 'int'> 99 <type 'int'> Black
Green 102 <type 'int'> 99 <type 'int'> AAA
White 104 <type 'int'> 99 <type 'int'> AAA
Red 100 <type 'int'> 99 <type 'int'> AAA
'AAA'
那么,你如何解决它?很简单:只需将回退值移到循环之外,因此您只需执行一次:
def value_for_value(d, str):
mykey = 'AAA'
for key, value in d.iteritems():
if value == str:
mykey = key
print key,value,type(value),str,type(str),mykey
return mykey
现在:
>>> value_for_value(Comp, 99)
Blue 101 <type 'int'> 99 <type 'int'> AAA
Ivory 103 <type 'int'> 99 <type 'int'> AAA
Black 99 <type 'int'> 99 <type 'int'> Black
Green 102 <type 'int'> 99 <type 'int'> Black
White 104 <type 'int'> 99 <type 'int'> Black
Red 100 <type 'int'> 99 <type 'int'> Black
'Black'
值得注意的是,如果您构建一个逆字典并对其进行索引,那么整个事情会更简单:
>>> CompInverse = {value: key for key, value in Comp.iteritems()}
>>> CompInverse.get(99, 'AAA')
'Black'