user1478335
user1478335

Reputation: 1839

Python dictionary editing entries

def replace_acronym(): # function not yet implemented
    #FIND
    for abbr, text in acronyms.items():
        if abbr == acronym_edit.get():
            textadd.insert(0,text) 
    #DELETE
    name = acronym_edit.get().upper()
    name.upper()
    r =dict(acronyms)
    del r[name]
    with open('acronym_dict.py','w')as outfile:
        outfile.write(str(r))
        outfile.close() # uneccessary explicit closure since used with...
    message ='{0} {1} {2} \n '.format('Removed', name,'with its text from the database.')
    display.insert('0.0',message)

    #ADD
    abbr_in = acronym_edit.get()
    text_in = add_expansion.get()
    acronyms[abbr_in] = text_in
    # write amended dictionary
    with open('acronym_dict.py','w')as outfile:
        outfile.write(str(acronyms))
        outfile.close()
    message ='{0} {1}:{2}{3}\n  '.format('Modified entry', abbr_in,text_in, 'added')
    display.insert('0.0',message)

I am trying to add the functionality of editing my dictionary entries in my tkinter widget. The dictionary is in the format {ACRONYM: text, ACRONYM2: text2...}

What I thought the function would achieve is to find the entry in the dictionary, delete both the acronym and its associated text and then add whatever the acronym and text have been changed to. What happens is for example if I have an entry TEST: test and I want to modify it to TEXT: abc what is returned by the function is TEXT: testabc - appending the changed text although I have (I thought) overwritten the file.

What am I doing wrong?

Upvotes: 3

Views: 437

Answers (1)

Zamphatta
Zamphatta

Reputation: 4724

That's a pretty messy lookin' function. The acronym replacement itself can be done pretty simple:

acronyms = {'SONAR': 'SOund Navigation And Ranging',
            'HTML': 'HyperText Markup Language',
            'CSS': 'Cascading Style Sheets',
            'TEST': 'test',
            'SCUBA': 'Self Contained Underwater Breathing Apparatus',
            'RADAR': 'RAdio Detection And Ranging',
           }

def replace_acronym(a_dict,check_for,replacement_key,replacement_text):
    c = a_dict.get(check_for)
    if c is not None:
        del a_dict[check_for]
        a_dict[replacement_key] = replacement_text
    return a_dict

new_acronyms = replace_acronym(acronyms,'TEST','TEXT','abc')

That works perfect for me (in Python 3). You could just call this in another function that writes the new_acronyms dict into the file or do whatever else you want with it 'cause it's no longer tied to just being written to the file.

Upvotes: 1

Related Questions