Python字典报错

# coding=utf-8


def init(data):
    data['first'] = {}
    data['middle'] = {}
    data['last'] = {}


def lookup(data, label, name):
    return data[label].get(name)


def store(data, full_name):
    names = full_name.split()
    if len(names) == 2: names.insert(1, '')
    labels = 'first', 'middle', 'last'
    for name, label in zip(labels, names):
        people = lookup(data, label, name)
        if people:
            people.append(full_name)
        else:
            data[label][name] = [full_name]


MyNames = {}
init(MyNames)
print MyNames
print MyNames['first'].get('liang')  #
store(MyNames, 'liang bing hui')

'''

C:\Python27\python.exe D:/liangbh/F/Lython/test7.py

Traceback (most recent call last):

{'middle': {}, 'last': {}, 'first': {}}

  File "D:/liangbh/F/Lython/test7.py", line 30, in <module>

None

    store(MyNames,'liang bing hui')

  File "D:/liangbh/F/Lython/test7.py", line 19, in store

    people = lookup(data, label, name)

  File "D:/liangbh/F/Lython/test7.py", line 11, in lookup

    return data[label].get(name)

KeyError: 'liang'

'''

慕神8560373
浏览 1583回答 3
3回答

angie

你在 get('liang')的时候,这个键还没定义呢,当然 get 失败呀,失败了就抛出 KeyError 异常咯
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python