Conditionally add dictionary in list

Question:

I have a request to collect user input as dictionary key/value.
If the key does not exist in current dictionary(dic1), add key/value into current dictionary(dic1).
If the key does exist, create a new dictionary(dic2) and a new list(list1), add both dic1 and dic2 to the list, overwrite dic1 by dic2 to allow script works on dic1, if the newly entered key does not exist in dic2, update dic2.
If the key does exist in dic2, do the same as above step.
Continue above steps until user stop entering.
Here is my code. If I have line (dic1=dic2.copy()), the IDE throw error saying cannot reference the dic1. I could not figure out the problem, can anyone point me to the right direction?

dic1 = {}
dic2 = {}
list1 = []
def collectinfo(continue_collect):
  while continue_collect == "yes":
    continue_collect = input("nrEnter yes to continue and no to stop: ")
    inputkey = input("nrEnter key: ")
    inputvalue = input("nrEnter value: ")
    if inputkey not in list(dic1.keys()):
      dic1[inputkey] = inputvalue
    else:
      list1.append(dic1)
      dic2[inputkey]=inputvalue
      dic1=dic2.copy()
      return collectinfo("yes")
Asked By: chun xu

||

Answers:

You are making a whole new dic1 dictionary local to the function because that is the way local and global objects work.

Line that is problematic:

dic1=dic2.copy()

Here you are declaring a local variable dic1 with the same name of the global one, so you are thrown a reference error.

You can use python global keyword to tell python interpreter you are trying to access the dictionaries in the global scope and modify their values, not create new dic1 variable local to the collectinfo function.

def collectinfo(continue_collect):
  global dic1 # change made here
  global dic2 # change made here
  while continue_collect == "yes":
    continue_collect = input("nrEnter yes to continue and no to stop: ")
    inputkey = input("nrEnter key: ")
    inputvalue = input("nrEnter value: ")
    if inputkey not in list(dic1.keys()):
      dic1[inputkey] = inputvalue
    else:
      list1.append(dic1)
      dic2[inputkey]=inputvalue
      dic1=dic2.copy()
      return collectinfo("yes")
Answered By: kesetovic
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.