How to refer to a dictionary using input string that is name of dictionary

Viewed 69

I write a code that creates the list of purchases in excel (shows price, name of each product and shows total price in the end).

For example it gets a some number of strings that are also dictionary names.

And it creates an excel file with a list of purchases, their price, and total price at the end.

I don't know what Dictionary it will be but I want to get a price which is a key pair.

Code: import openpyxl as xl

    Milk = {
    "name": "Milk",
    "price":  1,
    "id": "01",
    }
    
    Chicken = {
    "name": "Chicken",
    "price": 5,
    "id": "02"
    }
    wb = xl.load_workbook('List.xlsx')
    
    sheet = wb['Лист1']
    
    command = ''
    
    num = int(input())
    
    for row in range(2,num):
       command = input()
       
       value = command
       command = sheet.cell(row,1)
       command.value = value
       command = sheet.cell(row,2)
       key = 'price'
       
       command.value = command.get("price")
    wb.save('transactions3.xlsx')
1 Answers

I guess what you might be looking for is locals(), which keeps, among others, the available variables in the local scope, see this post.

my_dict = {'apples': 4}

# assume user input is `my_dict`
dict_name = input()

# return the dictionary's values
print(locals()[dict_name])

Just as a side note, instead of using openpyxl, I would recommend to use pandas dataframes, which implement .to_csv and .from_csv and to me is much more user friendly.

Related