简体   繁体   中英

Returning values from dictionary in python

switch = {(0,21): 'never have a pension',
          (21,50): 'might have a pension',
          (50,65): 'definitely have a pension',
          (65, 200): 'already collecting pension'}
for key, value in switch:
  a=input()
  if key[0] < a< key[1]:
        print(value)

when I try to execute the program it raise an error

TypeError: 'int' object is not subscriptable.

I don't know how to fix. please help

When you do for kev, value in switch , you're not getting the tuple and the string - you're getting the two values from the tuple. This is because iterating over a dictionary by default iterates over its keys.

Instead, you want to do for key, value in switch.items() .

I suppose you would like to do:

while True:
    try:
        a = int(input())
    except ValueError:
        print('not an int, try again')


for k, v in switch.items():
    if k[0] < a < k[1]:
        print(v)

And depending your needs:

>>> [v for k, v in switch.items() if k[0] < a < k[1]]
['might have a pension']

By the way, this is a fairly unpythonic way to do a multi-range test.

Consider this if-elif tree instead:

a = input()

if a < 21:
    msg = 'never have a pension'
elif a < 50:
    msg = 'might have a pension'
elif a < 65:
    msg = 'definitely have a pension'
else:
    msg = 'already collecting pension'

print msg

Advantages: it is simpler to understand, avoids duplicating the endpoints (which are most likely to change), works even if people somehow manage to live past 200, and actually avoids a bug in your original code (where people would already be collecting a pension if they were exactly 21).

Disadvantages: code is longer, and msg and a are repeated. However, this is offset by the fact that you can now implement more customizable and appropriate logic under each case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM