1

I've tried below code but it overwrites and makes duplicate of the last dictionary inputted.

name_lists=[]
d = {}
flag = ""
while(flag != "N"):
    d["name"] = input("Enter a name: ")
    d["surname"] = input("Enter a surname: ")
    d["patronmic"] = input("Enter a patronmic: ")
    d["id_number"] = input("Enter a worker's id number: ")
    name_lists.append(d)
    flag = input("Continue inputting data Y/N: ")
print(name_lists)
6
  • After appending d to name_lists, reset it to empty dict. Commented Oct 1, 2021 at 9:07
  • there is only one dictionary here. That is the problem. You keep appending the exact same dict multiple times to the list, name_lists.append(d) Commented Oct 1, 2021 at 9:09
  • @deceze (offtopic) how do you reference several duplicates when closing? Is this because someone already flagged the question? Commented Oct 1, 2021 at 9:10
  • 1
    @mozway How? With the edit button next to the duplicates. Not sure at what rep level you can use that. — Why? Because I'm closing as the first best duplicate I find, and sometimes find better ones afterwards, or multiple dupes may be necessary to answer a question in full. Commented Oct 1, 2021 at 9:13
  • ``` name_lists=[] d = {} flag = "" while(flag != "N"): d["name"] = input("Enter a name: ") d["surname"] = input("Enter a surname: ") d["patronmic"] = input("Enter a patronmic: ") d["id_number"] = input("Enter a worker's id number: ") name_lists.append(d) d = {} flag = input("Continue inputting data Y/N: ") print(name_lists) ``` Added a new statement to reinitialise d to an empty dict. Commented Oct 1, 2021 at 9:14

1 Answer 1

0

You need to move your d instantiation inside the loop, or you will overwrite the data at each step:

name_lists=[]
flag = ""
while(flag != "N"):
    d = {}
    d["name"] = input("Enter a name: ")
    d["surname"] = input("Enter a surname: ")
    d["patronmic"] = input("Enter a patronmic: ")
    d["id_number"] = input("Enter a worker's id number: ")
    name_lists.append(d)
    flag = input("Continue inputting data Y/N: ")
print(name_lists)

example output:

[{'name': 'a', ...}, {'name': 'b', ...}]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.