在python字典中迭代

2024-05-19 02:25:13 发布

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

抱歉,一个简单的问题,我想我得到的基本循环错误。我不知道为什么我没有得到预期的结果。你知道吗

Comp = {'Red':100, 'Blue':101, 'Green':102 ,'Ivory':103, 'White':104}
Comp ['Black'] = 99

def value_for_value(d, mynumber):
    for key, value in d.iteritems():
        print key,value,type(value),mynumber,type(mynumber)
        mykey = 'AAA'
        if value == mynumber:
            mykey = key
    return mykey

print value_for_value(Comp,99)

预期结果:黑色

实际结果:AAA

PS:为了确保我比较的是正确的数据类型,我也打印了数据类型。你知道吗


Tags: keyforvaluetype错误greenbluered
2条回答

我觉得这样写比较清楚:

def value_for_value(d, str):
    for k, v in d.iteritems():
        if v == str:
            return k
    return 'AAA'

key_for_value不是一个更有意义的名字吗?你知道吗

如果要在不修改d的情况下进行大量查找,那么按照@abarnert的建议创建反向dict是个好主意

问题是每次通过循环时,都会设置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'

值得注意的是,如果你构建一个逆dict并将其索引,整个过程会更简单:

>>> CompInverse = {value: key for key, value in Comp.iteritems()}
>>> CompInverse.get(99, 'AAA')
'Black'

相关问题 更多 >

    热门问题