› Forums › Python › ❓ Why does a dictionary value in Python change from a list to a string in this PhoneBook program?
- This topic is empty.
-
AuthorPosts
-
January 14, 2026 at 1:08 am #5938
Context (Code First)
Consider this simple phonebook design in Python:
class PhoneBook: def __init__(self): self.__persons = {} def add_number(self, name: str, number: str): if not name in self.__persons: # Create a list to store multiple phone numbers self.__persons[name] = [] self.__persons[name].append(number)This design allows one person to have multiple phone numbers.
A student asked:
What happens if we replace the last line with
self.__persons[name] = numberinstead of.append(number)?
❓ Q1. What does
self.__persons = {}actually mean?Answer:
It meansself.__personsis a dictionary.
But it does not mean its values must be lists.A Python dictionary can store any type as its values:
d = { "a": [], "b": "hello", "c": 42 }So even if
self.__personsstarts empty{}, its values can later become lists, strings, numbers, or anything else.
❓ Q2. Why does the original code use a list?
Answer:
Because one person can have more than one phone number.So the structure is:
{ "Alice": ["1234", "5678"], "Bob": ["9999"] }Each name points to a list of numbers, not a single number.
❓ Q3. What happens if we write
self.__persons[name] = number?Answer:
It replaces the list with a string.Example:
add_number("Alice", "1234")Dictionary becomes:
{"Alice": "1234"}Then:
add_number("Alice", "5678")Dictionary becomes:
{"Alice": "5678"}The old number
"1234"is lost.So the phonebook silently changes from:
One person → many numbers
to
One person → only one number
❓ Q4. Why does Python allow this?
Answer:
Because dictionaries do not enforce the type of their values.This is allowed:
d["x"] = [] d["x"] = "hello"Python assumes you know what you are doing.
It will not stop you from replacing a list with a string — even if that breaks your design.
❓ Q5. Why is
.append(number)the correct design?Answer:
Because you first created a list:self.__persons[name] = []So you must add to that list, not replace it:
self.__persons[name].append(number)This keeps all phone numbers for that person.
✅ Final takeaway
Your original design:
self.__persons[name].append(number)creates a real phonebook:
One dictionary → many people → each with many numbers
Replacing it with:
self.__persons[name] = numberdestroys that structure and turns it into:
One dictionary → many people → each with only one number
This is why that one line matters so much in data structure design.
-
AuthorPosts
- You must be logged in to reply to this topic.

