我必须在Python中创建一个应该具有以下功能的电话簿:
运行程序应如下所示:
telebok> add peter.forsberg 12345
telebok> lookup peter.forsberg
12345
telebok> alias peter.forsberg foppa
telebok> lookup foppa
12345
telebok> alias foppa MR21
telebok> change MR21 67890
telebok> lookup peter.forsberg
67890
除了改变之外,我得到了一切:
def adressbook():
telebook = {"jacob.engert":"8472923777", "nisse":"092563243"}
while True:
book = raw_input("telebook> ").lower()
lista = book.split()
if "add" in lista[0]:
n = lista[1]
x = lista[2]
if x in telebook.values():
print "Number already exists!"
elif n in telebook:
print "Name already exists!"
else:
telebook[n] = x
print telebook
elif "lookup" in lista[0]:
n = lista[1]
if n in telebook:
print n, "", telebook[n]
elif n.isdigit():
print "Type only characters!"
else:
print "This person does not exist!"
elif "alias" in lista[0]:
n = lista[1]
alias = lista[2]
if n in telebook:
v = telebook.get(n)
telebook[alias] = v
elif "change" in lista[0]:
key = lista[1]
value = telebook.get(key)
newvalue = lista[2]
for key, value in telebook.items():
telebook.update({key:newvalue})
print telebook
所以当我更新别名时,我也希望原始版本也能更新,但是我得到了这个结果:
>>> adressbook()
telebook> add ove 345347657
{'jacob.engert': '8472923777', 'ove': '345347657', 'nisse': '092563243'}
telebook> alias ove mr.o
telebook> lookup mr.o
mr.o 345347657
telebook> change mr.o 534523234
{'mr.o': '534523234', 'jacob.engert': '8472923777', 'ove': '345347657', nisse': '092563243'}
{'mr.o': '534523234', 'jacob.engert': '534523234', 'ove': '345347657', 'nisse': '092563243'}
{'mr.o': '534523234', 'jacob.engert': '534523234', 'ove': '534523234', 'nisse': '092563243'}
{'mr.o': '534523234', 'jacob.engert': '534523234', 'ove': '534523234', 'nisse': '534523234'}
telebook>
所以我的问题是,我怎样才能做到这一点,当我更改别名的数量时,原始数字也会改变?
答案 0 :(得分:0)
你几乎走在正确的轨道上。
为了更改所有条目(别名和父级),您需要查找与用户想要更改的条目具有相同编号的条目(无论是否为别名),并将其编号替换为新的:
key = lista[1]
newvalue = lista[2]
present_value = telebook.get(key)
if present_value:
for name, num in telebook.items():
if num == present_value:
telebook[name] = newvalue
或使用词典理解:
key = lista[1]
newvalue = lista[2]
present_value = telebook.get(key)
if present_value:
upd = {name: newvalue for name, num in telebook.items() if num == present_value }
telebook.update(upd)
或使用generator expression生成一系列元组(dict.update
同时接受这两者)
key = lista[1]
newvalue = lista[2]
present_value = telebook.get(key)
if present_value:
upd = ((name, newvalue) for name, num in telebook.items() if num == present_value)
telebook.update(upd)