I made my code like below....
But as i input the data such as spam & number, previous data is deleted.
So i'd like to make multiple value in one key... (i think using list is kinda good method)
For example,
Key: spam - Value: 01012341111, 01099991234,
Key: spam - Value: 01032938962, 01023421232, 01023124242
In summary, I want to get this print (attached Picture)
this is my code:
enter code here
phonebook = dict()
ntype = ['spam', 'friend', 'family', 'etc']
trash =[]
spam = []
friend = []
family = []
etc = []
while True:
a = input("Input your number and ntype : ")
b = a.split()
i = 0
j = 0
if a == 'exit':
print("end program")
break
exit()
elif a == "print spam":
print("*** spam numbers: ")
print('*', phonebook['spam'])
elif a == "print numbers":
print("*** numbers:")
for t in ntype:
try:
print("**", t)
print('*',phonebook[t])
except KeyError:
continue
print("** trash")
print("*", phonebook['trash'])
else:
while True:
try:
if ntype[j] in b:
for k in b:
if list(k)[0] == '0' and len(k) >= 10 and len(k) <= 11:
if k in phonebook.values():
print("Already Registered")
else:
phonebook[ntype[j]] = k
print(phonebook)
break
else:
j+=1
except IndexError:
if list(b[i])[0] == '0' and len(b[i]) >= 10 and len(b[i]) <= 11:
if b[i] in phonebook.values():
print("Already Registered")
else:
phonebook['trash'] = b[i]
print(phonebook)
break
else:
break
You should use list for that. The problem is that you cannot append to a value that has not yet been set.
And, as you saw, assigning multiple times to the same key won't do the trick.
So, in order to make it work you could initialize all your possible keys with an empty list:
This works but it's just tiring. Initializing dicts is a very common use case, so a method was added to
dict
to add a default value if it has not yet been set:But then again you would have to remember to call
setdefault
every time. To solve this the default library offersdefaultdict
.Which may just be what you need.
Hope I could help. ;)