0

I have a function as follows:

def control(qstat):
    gatnum = int(input("What number of control gates is this control qubit a part of?"))
    global qstatnum
    qstatnum = {}
    qstatnum[gatnum] = []
    qstatnum[gatnum].append(qstat) #seems to be a problem
    return qstat

However, there is a problem. Let's say I run it once. There will be one item in the list. Then, I run it a second time, with an item distinguishable from the second supposed to be added to the list. When I print qstatnum[gatnum], the list contains only the second item, leading me to believe that the .append() statement is somehow incorrectly written and overwriting any previous additions to the list.

Is this a correct diagnosis? Why would this be? Any help would be appreciated. Thanks!

Auden Young
  • 1,147
  • 2
  • 18
  • 39

2 Answers2

2

Each time you call the function, you are creating a new qstatnum dict, so the solution is to create the dictionary outside the function:

qstatnum = {}

def control(qstat):
    gatnum = int(input("What number of control gates is this control qubit a part of?"))
    try:
        qstatnum[qstat].append(gatnum)
    except:
        qstatnum[qstat] = [gatnum]
    return qstat

You need a try: except: block to verify if the key already exists in the dictionary, if it doesn't exists, just add the first value, else use append.

@DanD. approach seems to be shorter, please take a look:

qstatnum = {}

def control(qstat):
    gatnum = int(input("What number of control gates is this control qubit a part of?"))

    qstatnum.setdefault(qstat, []).append(gatnum)

    return qstat
slackmart
  • 4,754
  • 3
  • 25
  • 39
0

Every time the method is called, qstatnum is set to empty. So basically you are appending to nothing every time.

QB_
  • 109
  • 7