Making Phonebook in python : i want to get this screen by fixing my current code

2024/11/16 23:38:27

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

enter image description here

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 = 0j = 0if a == 'exit':print("end program")breakexit()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:continueprint("** 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]] = kprint(phonebook)breakelse:j+=1except 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)breakelse:break
Answer

You should use list for that. The problem is that you cannot append to a value that has not yet been set.

>>> d = {}
>>> d['a'].append('value')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
KeyError: 'a'

And, as you saw, assigning multiple times to the same key won't do the trick.

>>> d = {}
>>> d['a'] = 'value1'
>>> d['a'] = 'value2'
>>> d
{'a': 'value2'}

So, in order to make it work you could initialize all your possible keys with an empty list:

>>> d = {}
>>> possible_keys = ['a', 'b']
>>> for k in possible_keys:
...     d[k] = []
... 
>>> d['a'].append('value1')
>>> d['a'].append('value2')
>>> d['b'].append('value3')
>>> d['b'].append('value4')
>>> d
{'b': ['value3', 'value4'], 'a': ['value1', 'value2']}

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:

>>> d = {}
>>> d.setdefault('a', []).append('value1')
>>> d.setdefault('a', []).append('value2')
>>> d.setdefault('b', []).append('value3')
>>> d.setdefault('b', []).append('value4')
>>> d
{'b': ['value3', 'value4'], 'a': ['value1', 'value2']}

But then again you would have to remember to call setdefault every time. To solve this the default library offers defaultdict.

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['a'].append('value1')
>>> d['a'].append('value2')
>>> d['b'].append('value3')
>>> d['b'].append('value4')
>>> d['a']
['value1', 'value2']
>>> d['b']
['value3', 'value4']

Which may just be what you need.

Hope I could help. ;)

https://en.xdnf.cn/q/120270.html

Related Q&A

Adding enemies to a pygame platformer

Im new to pygame and trying to make a platformer game thats based on this tutorial: http://programarcadegames.com/python_examples/show_file.php?file=platform_scroller.pyI cant quite figure out how to …

Tips for cleaning up a challenges answer? Weighted Sum of Digits [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 8 years ago.Improve…

Get a variable as filename from python script and use it in a batch script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…

Python 3.x AttributeError: NoneType object has no attribute groupdict

Being a beginner in python I might be missing out on some kind of basics. But I was going through one of the codes from a project and happened to face this :AttributeError: NoneType object has no attri…

importing images from local folder instead of using Keras/Tensorflow dataset

Hi Can someone please help me to change this code so that it wont get data from keras mnist. instead it will be getting data from local folder. where do i need to make changes in it. and where in this …

why I have negative date by subtraction of two column?

Im trying to create a column his values is the subtraction of two column but I found strange values:Patient["Waiting"] = Patient["Appointment"] - Patient["Scheduled"]Sched…

Python 3: AttributeError: int object has no attribute choice [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Scraping web pages with Python vs PHP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

error switching to iframe selenium python

Currently Im attempting to switch to iframe/fancybox, but im getting the following error:line 237, in check_response raise exception_class (message, screen, stacktrace) selenium.common.exceptions.WebDr…