字典中存在的键的键错误

2024-10-03 00:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码,它有一个数组,循环遍历字典的键数组。它获取这些键中的每一个,将其应用于字典,然后获取返回值并使用它来分隔unicode表。示例:

sizeDict = {
    "Name": 16,
    "Mobile": 11,
    "Pizza": 7,
    "Drink": 7,
    "Dessert": 7,
    "Total": 7
}
header = ['name', 'mobile', 'pizza', 'drink', 'dessert', 'total']


def printRow(firstChar, endChar, space, specialChar, spaceArray, spaceDict):
    output = firstChar
    for i in range(0, len(spaceArray)):
        if(i == len(spaceArray) - 1):
            specialChar = endChar
        output = output + space * spaceDict[spaceArray[i].title()] + specialChar
    return output


print(printRow("┏", "┓", "━", "┳", header, sizeDict))
#Returns ┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━┓

出于某种原因,问题在于它无法将数组中的某些值识别为字典中的实际键,即使这两个字符串完全相同。以下是发生错误的特定数组、字典和错误消息

statHeader = ['Average Total', 'Earned', '% of Total']
statSizeDict = {
    "Average Total": 15,
    "Earned": 10,
    "% of Total": 20
}
statSizeArray = [15,10,20]
"""
<ipython-input-3-5c5f25401e4d> in statOrders(statData)
    272         for i in range(0, len(statHeader)):
    273             tempString += spaceVal(statHeader[i], statSizeDict[statHeader[i]])
--> 274         print(printRow("┏", "┓", "━", "┳", statHeader, statSizeDict))
    275         print(tempString)
    276         print(printRow("┣", "┫", "━", "╋", statHeader, statSizeDict))

<ipython-input-3-5c5f25401e4d> in printRow(firstChar, endChar, space, specialChar, spaceArray, spaceDict)
     51         if(i == len(spaceArray) - 1):
     52             specialChar = endChar
---> 53         output = output + space * spaceDict[spaceArray[i].title()] + specialChar
     54     return output
     55 # ========================================================================================================================== #

KeyError: '% Of Total'
"""

以下是完整的代码供参考:

import csv
import os
# ========================================================================================================================== #
data = []
testData = [8001, 499382, 'int', 'int', 'float']
header = ['name', 'mobile', 'pizza', 'drink', 'dessert', 'total']
statHeader = ['Average Total', 'Earned', '% of Total']
# ========================================================================================================================== #
orderDict = {
    "Small cheese pizza": ['pizza', 5],
    "Big cheese pizza": ['pizza', 10],
    "Small drink": ['drink', 1],
    "Large drink": ['drink', 1.5],
    "Small dessert": ['dessert', 0.5],
    "Large dessert": ['dessert', 1]
}
posDict = {
    "Pizza Total": 2,
    "Drink Total": 3,
    "Dessert Total": 4
}
returnDict = {
    1: 'Task completed succesfully.',
    2: 'Task encountered an unexpected error.',
    3: 'No file data was found.',
    4: 'Value does not exist or is out of range.',
    5: 'Value type is invalid or does not exist in current range.',
    6: 'Value length was to large for function.'
}
sizeDict = {
    "Name": 16,
    "Mobile": 11,
    "Pizza": 7,
    "Drink": 7,
    "Dessert": 7,
    "Total": 7
}
statSizeDict = {
    "Average Total": 15,
    "Earned": 10,
    "% of Total": 20
}
statSizeArray = [15,10,20]


def spaceVal(value, size):
    return str(value)[:size] + " " * (size-len(str(value))) + '┃'


def printRow(firstChar, endChar, space, specialChar, spaceArray, spaceDict):
    output = firstChar
    for i in range(0, len(spaceArray)):
        if(i == len(spaceArray) - 1):
            specialChar = endChar
        output = output + space * spaceDict[spaceArray[i].title()] + specialChar
    return output
# ========================================================================================================================== #


def newOrderCash(appendData, name, mobile, pizza=0, drink=0, dessert=0):
    """
    Appends the formatted order to the data list and returns
    the name of the customer and the total of their order.

    Args:

        appendData - a list which has the order
        appended to the end of it.
        name - a string value containing the customer's name.
        mobile - a string or integer value which contains
        the mobile number of the person making the order.
        pizza - the total cost of the ordered pizza which
        defaults to zero if no pizza was ordered.
        drink - the total cost of the ordered pizza which
        defaults to zero if no pizza was ordered.
        dessert - the total cost of the ordered pizza which
        defaults to zero if no pizza was ordered.

    Returns:
        A list containing the name of the customer and the
        total cost of their order.
        None - If name or mobile is not provided.
    """
    if(name is None or name == "" or mobile is None or mobile == ""):
        return None
    if(len(name) > 21 or len(str(mobile)) > 10):
        return 6
    total = float(pizza) + float(drink) + float(dessert)
    appendData.append([name, str(mobile), float(pizza), float(drink), float(dessert), total])
    returnData = name, total
    return list(returnData)


def newOrderItems(appendData, name, mobile, items):
    """
    Appends the formatted order to the data list and returns
    the name of the customer and the total of their order.

    Args:

        appendData - a list which has the order
        appended to the end of it.
        name - a string value containing the customer's name.
        mobile - a string or integer value which contains
        the mobile number of the person making the order.
        items - a list which contains the items the
        customer has ordered.

    Returns:
        A list containing the name of the customer and the
        total cost of their order.
        None - If name or mobile is not provided.
    """
    if(name is None or name == "" or mobile is None or mobile == ""):
        return None
    total = 0
    drink = 0
    dessert = 0
    pizza = 0
    for i in items:
        total += float(orderDict[i][1])
        if(orderDict[i][0] == 'pizza'):
            pizza += float(orderDict[i][1])
        elif(orderDict[i][0] == 'drink'):
            drink += float(orderDict[i][1])
        elif(orderDict[i][0] == 'dessert'):
            dessert += float(orderDict[i][1])
    tempArray = name, str(mobile), pizza, drink, dessert, total
    appendData.append(list(tempArray))
    returnData = name, total
    return list(returnData)


def newBulkOrders(appendData, names, mobiles, items):
    """
    Appends the formatted order to the data list and returns
    the names of the customer and the totals of their order.

    Args:

        appendData - a list which has the order
        appended to the end of it.
        name - a list containing the customers' names.
        mobiles - a list containing the customers' mobiles.
        items - a list of lists containing.

    Returns:
        A list containing the names of the customers
        and the totals of their orders.
        None - If name or mobile is not provided.
        Task Code 4 - If a type error occurs.
    """
    if(names is None or names == "" or mobiles is None or mobiles == ""):
        return None
    try:
        returnTotals = []
        returnNames = []
        errorArray = []
        returnList = []
        for l in range(0, len(names)):
            total = 0
            drink = 0
            dessert = 0
            pizza = 0
            tempItems = items[l]
            for i in tempItems:
                total += float(orderDict[i][1])
                if(orderDict[i][0] == 'pizza'):
                    pizza += float(orderDict[i][1])
                elif(orderDict[i][0] == 'drink'):
                    drink += float(orderDict[i][1])
                elif(orderDict[i][0] == 'dessert'):
                    dessert += float(orderDict[i][1])
            tempArray = names[l], str(mobiles[l]), float(pizza), drink, dessert, total
            returnTotals.append(total)
            returnNames.append(names[l])
            errorArray.append(list(tempArray))
        for x in range(0, len(errorArray)):
            appendData.append(errorArray[x])
        returnList = returnNames, returnTotals
        return list(returnList)
    except IndexError:
        return 4
# ========================================================================================================================== #


def saveOrder(saveData, filename):
    """
    Opens a file with name filename, and writes
    saveData to it.

    Args:

        saveData - the list of orders which will be
        written to the file.
        filename - a string value which gives the name
        of the file to be written to.

    Returns:
        Task Code 1 - If the task is complete successfully.
    """
    writeFile = csv.writer(open(filename, 'w', newline=''))
    writeFile.writerow(header)
    for i in range(0, len(saveData)):
        writeFile.writerow(saveData[i])
    return 1


def getOrders(writeData, filename):
    """
    Opens a file with name filename, and writes
    saveData to it.

    Args:

        saveData - the list of orders which will be
        written to the file.
        filename - a string value which gives the name
        of the file to be written to.

    Returns:
        Task Code 1 - If the task is complete successfully.
    """
    if os.path.isfile("pythoncsv.csv"):
        getFile = csv.reader(open(filename, 'r+', newline=''))
        for i in getFile:
            writeData.append(i)
        # Getting rid of header row so that we don't get a bunch of TypeErrors.
        writeData.pop(0)
        for i in writeData:
            i[2] = float(i[2])
            i[3] = float(i[3])
            i[4] = float(i[4])
            i[5] = float(i[5])
        print(writeData)
    else:
        # Creates file as above if statement tests whether it exists or not.
        getFile = csv.reader(open(filename, 'w', newline=''))
    return 1
# ========================================================================================================================== #


def printOrders(printData):
        # Purpose of first for loop is to ensure that longer names do not cause printing errors.
        space = 0
        tempString = "┃"
        for i in range(0, len(header)):
            tempString += spaceVal(header[i].title(), sizeDict[header[i].title()])
        print(printRow("┏", "┓", "━", "┳", header, sizeDict))
        print(tempString)
        print(printRow("┣", "┫", "━", "╋", header, sizeDict))
        tempString = ""
        for i in range(0, len(printData)):
            tempString = "┃"
            for x in range(0, len(printData[i])):
                tempString += spaceVal(printData[i][x], sizeDict[header[x].title()])
            print(tempString)
        print(printRow("┗", "┛", "━", "┻", header, sizeDict))
        print('\n')
        return 1
# ========================================================================================================================== #


def statOrders(statData):
    #try:
        statArray = [[0, 'Pizzas'], [0, 'Drinks'], [0, 'Desserts'], [0, 'Overall']]
        for i in range(0, len(statData)):
            statArray[0][0] += statData[i][2]
            statArray[1][0] += statData[i][3]
            statArray[2][0] += statData[i][4]
            statArray[3][0] += statData[i][5]
        space = 0
        tempString = "┃"
        for i in range(0, len(statHeader)):
            tempString += spaceVal(statHeader[i], statSizeDict[statHeader[i]])
        print(printRow("┏", "┓", "━", "┳", statHeader, statSizeDict))
        print(tempString)
        print(printRow("┣", "┫", "━", "╋", statHeader, statSizeDict))
        tempString = ""
        for i in range(0, len(statArray)):
            tempString = "┃"
            tempString = tempString + spaceVal(statArray[i][1], statSizeArray[0]) + spaceVal(str(statArray[i][0]), statSizeArray[1]) + spaceVal(str(int(100 * statArray[i][0] / statArray[3][0])) + '%', statSizeArray[2])
            print(tempString)
        print(printRow("┗", "┛", "━", "┻", statHeader, statSizeDict))
        print('\n')
        return 1
    #except (IndexError, TypeError):
     #   return 5
# ========================================================================================================================== #


def modifyOrder(modifyData, orderName, modifyValueType, newValue):
    try:
        for i in range(0, len(modifyData)):
            if(modifyData[i][0] == orderName):
                modifyData[i][posDict[modifyValueType]] = float(newValue)
                modifyData[i][5] = float(sum(modifyData[i][2:5]))
                return modifyData[i][5]
        return 4
    except (TypeError, IndexError):
        return 2
# ========================================================================================================================== #
# End of Asserts: Task Failed Succesfully
# ========================================================================================================================== #


以及发生错误的具体函数:

def statOrders(statData):
    #try:
        statArray = [[0, 'Pizzas'], [0, 'Drinks'], [0, 'Desserts'], [0, 'Overall']]
        for i in range(0, len(statData)):
            statArray[0][0] += statData[i][2]
            statArray[1][0] += statData[i][3]
            statArray[2][0] += statData[i][4]
            statArray[3][0] += statData[i][5]
        space = 0
        tempString = "┃"
        for i in range(0, len(statHeader)):
            tempString += spaceVal(statHeader[i], statSizeDict[statHeader[i]])
        print(printRow("┏", "┓", "━", "┳", statHeader, statSizeDict))
        print(tempString)
        print(printRow("┣", "┫", "━", "╋", statHeader, statSizeDict))
        tempString = ""
        for i in range(0, len(statArray)):
            tempString = "┃"
            tempString = tempString + spaceVal(statArray[i][1], statSizeArray[0]) + spaceVal(str(statArray[i][0]), statSizeArray[1]) + spaceVal(str(int(100 * statArray[i][0] / statArray[3][0])) + '%', statSizeArray[2])
            print(tempString)
        print(printRow("┗", "┛", "━", "┻", statHeader, statSizeDict))
        print('\n')
        return 1
    #except (IndexError, TypeError):
     #   return 5
# ========================================================================================================================== #

Tags: ofthenameinforlenreturnfloat