Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reassign dictionary key values

I have this dictionary

brands = {
1: 'BPR Performance Rimfire',
2: 'M22',
3: 'M22 Subsonic',
4: 'Super Suppressed',
5: 'Super X',
6: 'USA',
7: 'Varmint HE',
8: 'Varmint LF',
9: 'Wildcat',
10: 'Xpert', }

and depending on some user selection I want to display a subset of this dictionary in the form of a menu, which I can do but I would like to update the keys so that if I’m only showing three elements such as

1 -- BPR Performance Rimfire
5 -- Super X
7 -- Varmint HE

I could reassign the number corresponding to the option, for example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1 -- BPR Performance Rimfire
2 -- Super X
3 -- Varmint HE

To do so, I have made these two functions

def entries_to_remove(entries, dictionary):
    for key in entries:
        if key in dictionary:
            del dictionary[key]

def update_keys(dictionary):
    dict_copy = dictionary.copy()
    key_n = 1
    for k in dictionary:
        dict_copy[key_n] = dict_copy.pop(k)
        key_n = key_n + 1
    return dict_copy

then I define the entries to remove, which works

entries = (2, 3, 4, 6, 9, 10)
entries_to_remove(entries, brands)

and then call

brands = update_keys(brands)

which gives me an error in the function entries_to_remove

  File "C:\Users\teide\Documents\Guns\moa_clicks.py", line 70, in addBullet
entries_to_remove(entries, brands)
                           ^^^^^^
UnboundLocalError: cannot access local variable 'brands' where it is not associated with a value

If I comment out brands = update_keys(brands) the code executes normally and gives me the expected result

Choose brand
1 -- BPR Performance Rimfire
5 -- Super X
7 -- Varmint HE
8 -- Varmint LF

I don’t understand what I’m doing wrong and some help would be greatly appreciated.

I’m adding the full code that I have at the moment

menu_options = {
    1: 'Add bullet type',
    2: 'Calculate MOA clicks',
    3: 'Exit',
}

cartridge_types = {
    1: '17 HMR',
    2: '17 Win Super Mag',
    3: '22 Long',
    4: '22 Long Rifle',
    5: '22 Short',
    6: '22 Win Mag',
    7: '22 WRF',
}

brands = {
    1: 'BPR Performance Rimfire',
    2: 'M22',
    3: 'M22 Subsonic',
    4: 'Super Suppressed',
    5: 'Super X',
    6: 'USA',
    7: 'Varmint HE',
    8: 'Varmint LF',
    9: 'Wildcat',
    10: 'Xpert',
}
      
def print_menu(menu):
    for key in menu.keys():
        print (key, '--', menu[key] )  
        

def entries_to_remove(entries, dictionary):
    for key in entries:
        if key in dictionary:
            del dictionary[key]

def update_keys(dictionary):
    dict_copy = dictionary.copy()
    key_n = 1
    for k in dictionary:
        dict_copy[key_n] = dict_copy.pop(k)
        key_n = key_n + 1
    return dict_copy

def addBullet():  
        name = str(input('Enter bullet name: '))
        print('Choose cartridge type')
        print_menu(cartridge_types)
        cType = cartridge_types.get(int(input()))
        if cType == cartridge_types.get(1):
            entries = (2, 3, 4, 6, 9, 10)
            entries_to_remove(entries, brands)
            #brands = update_keys(brands)
            
        print('Choose brand')
        print_menu(brands)
        brand = brands.get(int(input()))
        


while(True):
    print_menu(menu_options)
    option = int(input('Enter your choice: ')) 
    if option == 1:
        addBullet()
    elif option == 2:
        calculateMOA()
    elif option == 3:
        print('Goodbye')
        exit()
    else:
        print('Invalid option. Please enter a number between 1 and 3.')
        

>Solution :

Modify your addBullet function to use the brands dictionary correctly:

def addBullet():
    global brands  # Declare brands as a global variable
    name = str(input('Enter bullet name: '))
    print('Choose cartridge type')
    print_menu(cartridge_types)
    cType = cartridge_types.get(int(input()))
    if cType == cartridge_types.get(1):
        entries = (2, 3, 4, 6, 9, 10)
        entries_to_remove(entries, brands)
        brands = update_keys(brands)  # Update the global brands dictionary
    print('Choose brand')
    print_menu(brands)
    brand = brands.get(int(input()))

Now, when you call brands = update_keys(brands) inside the function, it should work without any errors, and your brands dictionary will be updated with the modified keys as you intended.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading