# 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.pyTraceback (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''''
添加回答
举报
0/150
提交
取消