简体   繁体   中英

Chinese characters as dictionary KEY

I am trying to create a dictionary lookup variable like this:

lookup = {
    u'安徽省':'Anhui',
    u'福建省':'Fujian',
    u'甘肃省':'Gansu',
    u'广东省':'Guangdong',
    u'贵州省':'Guizhou',
    u'浙江省':'Zhejiang'
}

I am calling an API and it returns the result in Chinese. I want to simply have a look up table to convert it to the English name.

So my code is:

api_response = api.geocode(address, isChina)
if len(api_response['Response']['View']) > 0:
        state = lookup[api_response['Response']['View'][0]['Result'][0]['Location']['Address']['State']]

But the error I get is:

2019-07-29 15:35:13.193 | ERROR    | __main__:<module>:148 - Traceback (most recent call last):   File "format.py", line 93, in <module>
    new_dict = doStepByStepCleanse(row, isChina, line_count)   File "format.py", line 43, in doStepByStepCleanse
    state =  lookup[api_response['Response']['View'][0]['Result'][0]['Location']['Address']['State']] KeyError: '山东省'

Is this possible to achieve?

If you read the error, I'm not sure you've defined all possible keys that the API returns. There's nothing special about the Chinese characters being in the dictionary, just that KeyError: '山东省' means that it really isn't there in your dictionary

If you're not guaranteed to have all known keys ahead of time, you should fallback to getting a default value

lookup.get(api_response['Response']['View'][0]['Result'][0]['Location']['Address']['State']], "Unknown") 

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