0

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("\n\rEnter yes to continue and no to stop: ")
    inputkey = input("\n\rEnter key: ")
    inputvalue = input("\n\rEnter value: ")
    if inputkey not in list(dic1.keys()):
      dic1[inputkey] = inputvalue
    else:
      list1.append(dic1)
      dic2[inputkey]=inputvalue
      dic1=dic2.copy()
      return collectinfo("yes")
chun xu
  • 393
  • 1
  • 4
  • 13
  • Welcome to Stack Overflow. Next time, please show a [complete](https://meta.stackoverflow.com/questions/359146/) error message, by copying and pasting, starting from the line that says `Traceback (most recent call last):`, and formatting it like code. Do not say things like " the IDE throw error saying cannot reference the dic1" - that makes us guess. Please also read [mre]. – Karl Knechtel Sep 25 '22 at 23:10

1 Answers1

0

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("\n\rEnter yes to continue and no to stop: ")
    inputkey = input("\n\rEnter key: ")
    inputvalue = input("\n\rEnter value: ")
    if inputkey not in list(dic1.keys()):
      dic1[inputkey] = inputvalue
    else:
      list1.append(dic1)
      dic2[inputkey]=inputvalue
      dic1=dic2.copy()
      return collectinfo("yes")
kesetovic
  • 144
  • 6