将字典中的某些值相乘

时间:2019-02-24 11:02:56

标签: python python-3.x

我正在编写一个程序,允许用户从菜单中选择选项,并在此基础上打印所选选项的详细信息。我需要将数量和价格相乘才能得出成本。问题是,我的价格和数量都在嵌套词典中。如果用户选择选项1> 3AB,则应根据3AB的数量和价格打印出成本。我该怎么办?

    stock = {
        '3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
        'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
        'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
        }

def menu():
    menuChoice =True

    while menuChoice:
        print ("""
        Menu
        1. List Holding and Sold details for a Stock
        2. Buy Stock
        3. Sell Stock
        4. list Holdings
        5. list Sold Stock
        0. Exit
        """)

        menuChoice= input("Enter Choice:  ")
        if menuChoice=="1": 
            option1()
        elif menuChoice=="2":
           print("\n Buy Stock") 
        elif menuChoice=="3":
           print("\n Sell Stock") 
        elif menuChoice=="4":
           print("\n List Holdings") 
        elif menuChoice=="5":
           print("\n List Sold Stock") 
        elif menuChoice=="0":
            break 
        elif menuChoice !="":
             print("\n Invalid. Please Re-enter choice: ")


def option1():
    input1 = input("Please enter code: ").lower()
    test = stock['3AB']['Volume'] * stock['3AB']['Price']
    print(test)
    if input1.upper() == "3AB":
        print("\nCode: " + input1.upper())
        print("Name: " + stock['3AB']['Name'])
        print("Last Purchase Date: " + stock['3AB']['Purchase Date'])
        print("Average Price: " + stock['3AB']['Price'])
        print("Volume: " + stock['3AB']['Volume'])
        print("Investment Cost ($): " + ())

    elif input1.upper() == "S12":
        print("\nCode: " + input1.upper())
        print("Name: " + stock['S12']['Name'])
        print("Last Purchase Date: " + stock['S12']['Purchase Date'])
        print("Average Price: " + stock['S12']['Price'])
        print("Volume: " + stock['S12']['Volume'])

    elif input1.upper() == "AE1":
        print("\nCode: " + input1.upper())
        print("Name: " + stock['AE1']['Name'])
        print("Last Purchase Date: " + stock['AE1']['Purchase Date'])
        print("Average Price: " + stock['AE1']['Price'])
        print("Volume: " + stock['AE1']['Volume'])

    else:
        print("Stock is not found in your portfolio.")
        print(input("Enter another option: "))

menu()

2 个答案:

答案 0 :(得分:0)

问题是您将值作为字符串存储在原始字典中。要解决此问题,您只需将值转换为float即可:

test = float(stock['3AB']['Volume']) * float(stock['3AB']['Price'])

或者不要更改代码并将值存储为数字:

stock = {
        '3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': 1.55, 'Volume':3000},
        'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': 3.25, 'Volume': 2000},
        'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': 1.45, 'Volume': 5000}
        }

顺便说一句,在下面的代码中,您的代码仍然存在一个问题。您必须定义一个要打印的值:

print("Investment Cost ($): " + ())

答案 1 :(得分:0)

您需要在字典中输入数字-而不是字符串。您还可以通过使用字典而不是大型的if-elif-construct来调用函数来使代码“更灵活”。使用函数来请求数字/输入也是减少重复编码的好方法(DRY-不要重复自己):

在字典中固定数字(或直接使用数字):

stock = {
        '3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 
                'Price': float('1.55'), 'Volume': int('3000')},
        'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018',    
                'Price': float('3.25'), 'Volume': int('2000')},
        'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018',  
                'Price': float('1.45'), 'Volume': int('5000')} } 

不要重复自己:

def inputNumber(text,r):
    """Handles numeric input - input must be inside r (f.e. a range/set/list)."""
    while True:
        try:
            choice = int(input(text))
            if choice in r:
                return choice
        except ValueError:
            print("Wrong choice - try again.")

def inputTextUpper(r):
    """Handles text input - text must be inside r (a list/set/...) and is returned as
     upper(). If nothing is inputted the function returns None."""
    while True:
        try:
            choice = input("Choose one: {} - return to skip.".format(str(r))).upper()
            if choice in r:
                return choice
            elif not choice:
                return None  # empty input
        except ValueError:
            print("Wrong choice - try again.")

映射函数以输入并调用它们:

def buy():
    input1 = inputTextUpper([x for x in stock.keys()])
    what = stock.get(input1) # get the inner dict or None if empty input

    if not what:
        print("Back to main menue")
        return

    # using , instead of + to avoid errors when print numbers - you should probably
    # read about str.format() or f""-strings to make formatting "better"
    print("\nCode: ", input1)
    print("Name: ", what['Name'])
    print("Last Purchase Date: ", what['Purchase Date'])
    print("Average Price: ", what['Price'])
    print("Volume: ", what['Volume'])
    print("Investment Cost ($): ", what['Volume']*what['Price'])

def dummy():
    print("Not implemented")

def menu():

    # map an input to a function call (the name of the function to be called)
    funcMapp = {1:buy, 2:dummy, 3:dummy, 4:dummy,5:dummy} # lots of dummies

    while True:
        menuChoice = inputNumber("""
        Menu
        1. List Holding and Sold details for a Stock
        2. Buy Stock
        3. Sell Stock
        4. list Holdings
        5. list Sold Stock
        0. Exit
        """, range(6))
        if menuChoice == 0:
            break
        # execute the function choosen    

        funcMapp[menuChoice] ()  # this gets the function from the dict and calls it


menu()

一次运行的输出:

        Menu
        1. List Holding and Sold details for a Stock
        2. Buy Stock
        3. Sell Stock
        4. list Holdings
        5. list Sold Stock
        0. Exit
        Dunno
Wrong choice - try again.

        Menu
        1. List Holding and Sold details for a Stock
        2. Buy Stock
        3. Sell Stock
        4. list Holdings
        5. list Sold Stock
        0. Exit
        2
Not implemented

        Menu
        1. List Holding and Sold details for a Stock
        2. Buy Stock
        3. Sell Stock
        4. list Holdings
        5. list Sold Stock
        0. Exit
        1
Choose one: ['3AB', 'S12', 'AE1'] - return to skip.None
Choose one: ['3AB', 'S12', 'AE1'] - return to skip.asdf
Choose one: ['3AB', 'S12', 'AE1'] - return to skip.3ab

Code:  3AB
Name:  Telcom
Last Purchase Date:  12/12/2018
Average Price:  1.55
Volume:  3000
Investment Cost ($):  4650.0

        Menu
        1. List Holding and Sold details for a Stock
        2. Buy Stock
        3. Sell Stock
        4. list Holdings
        5. list Sold Stock
        0. Exit
        1
Choose one: ['3AB', 'S12', 'AE1'] - return to skip.
Back to main menue

        Menu
        1. List Holding and Sold details for a Stock
        2. Buy Stock
        3. Sell Stock
        4. list Holdings
        5. list Sold Stock
        0. Exit
        0 

有关如何避免KeyError的问题,请参见Why dict.get(key) instead of dict[key]?,有关更多格式化选项的信息,请参见string formating