Skip to content Skip to sidebar Skip to footer

Making Phonebook In Python : I Want To Get This Screen By Fixing My Current Code

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 k

Solution 1:

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. ;)

Post a Comment for "Making Phonebook In Python : I Want To Get This Screen By Fixing My Current Code"