dictionary - Python - Switch/Case using a Dictionnary implies the interpretation of each case -


in aim of emulating switch/case block using dictionary, noticed isn't supposed occur:

print {     'a': 1,     'b': 2 + '',     'c': 3, }['a'] 

i'm expecting that, since key given 'a' => second line (key b) shouldn't interpreted.

but is:

'b': 2 + '', typeerror: unsupported operand type(s) +: 'int' , 'str' 

which means second line has been interpreted anyway.

somebody has explanation phenomenon?
or way emulate switch without implying python interprets each case?

python doesn't use lazy evaluation, has create entire dictionary before can access element of ['a']. if part of dictionary creation gets error, fail @ part.

if want emulate switch/case, including fact doesn't execute bodies of unselected cases, can put functions dictionary.

print {     'a': lambda: 1,     'b': lambda: 2 + '',     'c': lambda: 3 }['a']() 

for more info this, see

why doesn't python have switch/case?


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -