I have to create a phonebook in Python that should have the following functions:
Running the program should look like this:
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
I got everything to work except for change:
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
So when I update the alias, I want the original to update as well, but I get this result:
>>> 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>
So my question is, how can I make it so that when I change the number for the alias, the number for the original will also change?
You are almost on the right track.
In order to change all the entries (aliases and parent), you need to look for those entries which have the same number as the entry the user wants to change (be it an alias or not) and replace their number with the new one:
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
or use a dictionary comprehension:
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)
or use a generator expression to generate a sequence of tuples (dict.update
accepts both)
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)