iterating over in a python dictionary -


sorry simple question, guess getting basic looping wrong. not sure why not geting expected result.

comp = {'red':100, 'blue':101, 'green':102 ,'ivory':103, 'white':104} comp ['black'] = 99  def value_for_value(d, mynumber):     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) 

expected result : black

actual results : aaa

ps: make sure comparing correct data types, have printed data types well.

the problem every time through loop, set mykey = 'aaa'. so, unless str happens last value, overwrite right answer wrong one.

let's add more prints see better:

def value_for_value(d, str):     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' 

so, how fix it? simple: move fallback value outside loop, once:

def value_for_value(d, str):     mykey = 'aaa'     key, value in d.iteritems():         if value == str:             mykey = key         print key,value,type(value),str,type(str),mykey     return mykey 

now:

>>> 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' 

it's worth noting whole thing simpler if built inverse dict , indexed it:

>>> compinverse = {value: key key, value in comp.iteritems()} >>> compinverse.get(99, 'aaa') 'black' 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -