0

so I'm trying to get information from the user , asking him to enter his name and his age and store the values in a dictionary , each dictionary is put inside a table T once the user finishes it shows all dictionaries have the same values for a reason that I don't know

T=[dict()]*3
for i in range(3):
   T[i]["Name"] = input('Enter name')
   T[i]["Age"] = int(input('Enter age'))
print(T)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Welcome to Stack Overflow. Please read [ask] so that you can ask better questions going forward. Here, my objection is that the *question you are asking* is about a *problem* wherein the dicts have the same contents. Since they have *some* contents, clearly you are able to "get input for dictionaries", so that isn't the right thing to say in the question title - I have retitled it. You may also want to read ["How much research is expected of Stack Overflow users?"](https://meta.stackoverflow.com/questions/261592). – Karl Knechtel Dec 16 '21 at 23:08

2 Answers2

1

When you do this:

T=[dict()]*3

What's happening is that a dict is created, put in a list and that list is then replicated three times as a single list - containing three references to the same dict. It's similar to:

d = dict()
T = [d]
for __ in range(2):
   T.extend(T)

You could instead:

T = [dict() for __ in range(3)]

This creates a list with three separate dicts.

By the way, you shouldn't name variables with capital letters in Python, to avoid confusion with class names - t would be a better name.

Grismar
  • 27,561
  • 4
  • 31
  • 54
0

Try

T=[dict() for _ in range(3)]
for i in range(3):
   T[i]["Name"] = input('Enter name')
   T[i]["Age"] = int(input('Enter age'))
print(T)

user23952
  • 578
  • 3
  • 10