简体   繁体   中英

Python Printing 3 values inside a dictionary

I don't think my long code is necessary for this question, but I have a program that gives me the average of all numbers entered, all positive numbers entered, and all non positive numbers entered.

# Receive number inputs from user, turning it into a list.
def getInput():
    numList = []
    while True:
        z = float(input("Enter a number (-9999 to quit): "))
        if z == -9999:
            return numList
        else:
            numList.append(z)



numList = getInput()

# Splitting the whole list of numbers into positive list, and non positive list.
def splitPosNonPos():
    posList=[]
    nonPosList=[]
    for z in numList:
        if z > 0:
            posList.append(z)
        else:
            nonPosList.append(z)

    return (posList, nonPosList)

posList, nonPosList = splitPosNonPos()
print()
print("All numbers ", numList)
print("Positive numbers ", posList)
print("Non positive numbers ", nonPosList)

# finding the average of all numbers
def computeAllAvg():
    average = 0
    sum = 0    
    for n in numList:
        sum = sum + n
    average = sum / len(numList)
    return average

allNumAvg = computeAllAvg()


# finding the average of positive numbers
def computePosAvg():
    average = 0
    sum = 0    
    for n in posList:
        sum = sum + n
    average = sum / len(posList)
    return average

posNumAvg = computePosAvg()


# finding average of non positive numbers
def computeNonPosAvg():
    average = 0
    sum = 0    
    for n in nonPosList:
        sum = sum + n
    average = sum / len(nonPosList)
    return average

nonPosNumAvg = computeNonPosAvg()

print("All num average ", allNumAvg)
print("Pos num average ", posNumAvg)
print("Non Pos num average ", nonPosNumAvg)

My values allNumAvg, posNumAvg, and nonPosNumAvg all return me floats which I can easily print, but this isn't currently how I want to print them. I need to be able to present them in a dictionary, so that the actual output looks like this-

{'AvgPositive': (The positive float), 'AvgNonPos': (non positive number float), 'AvgAllNum': (all number float)}

Is there some sort of function where I can take my three values, assign them to those three keys and present them like that?

Thank you!

print({'AvgPositive': posNumAvg,
       'AvgNonPos': nonPosNumAvg,
       'AvgAllNum': allNumAvg})

I don't know why you'd want to print your output in a dict, though. You're not going to be able to control what order the key-value pairs occur in, and it's not the most readable of formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM