在python中分配动态密钥字符串

时间:2012-07-09 07:20:04

标签: python string dictionary

我想做这样的事情,是否可以在python中使用。

f = 'free'
p = 'paid'
if version is f:
      APP_VER = 'APP_FREE'
elif version is p:
      APP_VER = 'APP_PAID'

s_email = webapp2.get_app().config[APP_VER]['SUPPORT_EMAIL']

Error: UnboundLocalError: local variable 'APP_VER' referenced before assignment

任何想法!

1 个答案:

答案 0 :(得分:5)

if version is f:
      APP_VER = 'APP_FREE'
elif version is p:
      APP_VER = 'APP_PAID'

有可能version既不是f也不是p。包含else部分。另外(正如@jamylak所说)使用==来比较字符串,而不是is

if version == f:
      APP_VER = 'APP_FREE'
elif version == p:
      APP_VER = 'APP_PAID'
else:
    print 'version <{0}> unknown'.format(version)
    exit()
    # or raise an exception here

另一种方式(如果版本列表更长,则会有很大改进):

app_name = {'free': 'APP_FREE',
            'paid': 'APP_PAID'} # this can be extended if needed
APP_VER = app_name.get(version)
# APP_VER is None if version unknown