[Tutor] adding new keys to a nested dict

mhysnm1964 at gmail.com mhysnm1964 at gmail.com
Sat Jan 22 23:09:13 EST 2022


Hello all

 

I am trying to add new keys to a dict and finding the previous key is being
overridden. Below is the structure:

 

newScore {'Bar 1': {

               'Time signature': "text",

               'tempo': 'tempo',

               'beat 1': { 'voice 1': {} },

               },

}

 

As you can tell by the code below. I am starting with an empty dict. In the
code I am dynamically creating the nested dict. I am finding when I add the
time signature key under the 'bar 1' dict node. It is being overridden,
rather than adding a new key. Not sure why this is occurring. I can add
nested dicts with one key value. I want to be able to insert a new key and
keep the existing keys in that dict node as outline.

 

newScore = {}

bar = '' # stores the current bar being worked upon.

beat = '' # stores the current beat being worked upon.

voice = '' # stores the current voice being worked upon.

 

for notation in score:

    if notation[0] == 'Barline Single barline':

        notation.pop(0) # remove the matched pattern.

        for word in notation:

            if word.startswith('Bar'):

                if word not in newScore:

                    bar = word

                    newScore[bar] = {}

            elif word.startswith('Beat'):

                if word not in newScore[bar]:

                    beat = word

                    voice = 'Voice 1'

                    newScore[bar][beat] = { voice: []}

            #else:

                #newScore[bar][beat][voice].append(word)

    elif notation[0].startswith('Vertical Frame'):

        if 'Vertical Frame' not in newScore:

                newScore['Vertical Frame'] = notation

    elif notation[0].startswith('Time Signature'):

        # include time signature regardless if it is the same under the
right beat and voice.

        #print (notation)

        newScore[bar] = {'Time Signature': notation[0]} 

        # newScore[bar]['Time Signature'] = notation[0] # syntax error 

    elif notation[0].startswith('Treble clef'):

        #print (notation)

        newScore[bar]['clef'] =notation[0]

    elif notation[0].startswith('Rest '):

        print (notation)

        for i in range(0, len(notation)):

            if notation[i] == beat:

                notation.pop(i) # remove the word beat value.

                # newScore[bar][beat][voice].append(notation)

 

I keep getting syntax errors or the 'beat' and other keys within the 'bar 1'
are removed only leaving the last dict key. It only occurs in the nested
dict. What am I doing wrong.

 



More information about the Tutor mailing list