开发者

Look up value in Django json object

In a Django view I have an object

state_lookup = {"Alabama":"AL", "Alaska":"AK", ... "Wyoming":"WY"}

How do I pass a state name to that 开发者_Python百科object and get its abbreviation in return?


Python dictionaries can be accessed in the same way as lists. Here is an example.

state_lookup = {"Alabama":"AL", "Alaska":"AK", ... "Wyoming":"WY"}
state = 'Alabama'
abbrev = state_lookup[state] # abbrev should be 'AL' now


Mao answer is exact.
Just one note if there is no such key than you'll get an exception. So sometimes you may want to use:

state = 'Alabama'
state_wrong = 'Alibama'

#to get key value with default defined
abbrev = state_lookup.get(state_wrong,None)
assert abbrev == None

#in case of more if... flow
if state_lookup.has_key(state_wrong):
    abbrev = state_lookup[state_wrong]
else:
    abbrev = None
assert abbrev == None

To quickly get to speed in python I strongly recommend going through examples from: http://www.siafoo.net/article/52

Good luck on your python journey!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜