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)
  • After appending d to name_lists, reset it to empty dict. – codefire Oct 01 '21 at 09: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)` – juanpa.arrivillaga Oct 01 '21 at 09:09
  • @deceze (offtopic) how do you reference several duplicates when closing? Is this because someone already flagged the question? – mozway Oct 01 '21 at 09: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. – deceze Oct 01 '21 at 09: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. – codefire Oct 01 '21 at 09:14
  • @deceze I guess I don't have access to this function yet, but good to know that it exists! Thanks for the response. – mozway Oct 01 '21 at 09:16

1 Answers1

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', ...}]
mozway
  • 194,879
  • 13
  • 39
  • 75