简体   繁体   中英

Can anyone help me with finding the average of dictionary python 2.7?

I am having problems iterating over my dictionary. The program should print the average of the numbers beside each name in the dictionary. Can anyone help me figure it out what I'm doing wrong? The following is my current code:

guest={"Mary":"15", "Joe":"13", "Dustin":"12"}

def CalcAverage(guest):
    total = 0.0
    numPersons = 0
    for key,value in guest.items():
        numPersons += len(guest[key])
        total = float(sum(guest[value]))
    return total/numPersons

print CalcAverage(guest)

What you are doing wrong:

  1. key and value already contain the key and value from the dictionary. There is no need to access the dictionary again as in guest[key] .
  2. numPersons should be incremented by 1 on each iteration of the loop, not by the length of the value which is what len(guest[key]) does.
  3. total should accumulate the total of the values, not be assigned to each one, ie total += float(value) .

Correcting those 3 items yields code like this:

guest= {"Mary":"15", "Joe":"13", "Dustin":"12"}

def CalcAverage(guest):
    total = 0.0
    numPersons = 0
    for key, value in guest.items():
        numPersons += 1
        total += float(value)
    return total / numPersons

>>> CalcAverage(guest)
13.333333333333334

You can simplify this by using a generator expression to convert each value to a float, sum those floats, then divide by the number of items in the guest dictionary:

def CalcAverage(guest):
    return sum(float(v) for v in guest.values()) / len(guest)

>>> CalcAverage(guest)
13.333333333333334

You have been defining your numbers a strings, which makes them less easy to handle. Better would be:

guest={"Mary": 15, "Joe": 13, "Dustin": 12}

Or as floats already:

guest={"Mary": 15.0, "Joe": 13.0, "Dustin": 12.0}

Also you used float(sum(guest[value]) which has two major issues:

  • guest[value] tries to get the value with the key stored in value from the dictionary. But value is no key, that can't work.
  • You are having string values only, you can't sum them with sum() .

There are many other problems in the code, some examples:

  • for key,value in guest.items(): makes the key and they value avaible as key and value in the for block. You don't need to index guest later. That means that guest[key] is the same as value .
  • len(guest[key]) would return the length of value , which is a number and would return 2 (all your number strings have two digits).

What you want to archive can be done much more easy:

def calc_average(guest)
    length = len(guest)
    values = [float(value) for value in guest.values()]
    return sum(values) / length

The first line gets the length of the dictionary. The second line pull all values from the list and converts them to floats. This is a list comprehension. The last line sums the values and returns the average. BTW: I also adapted the name of the function to the usual Python naming convention for functions.

Value is a str type you can convert into float and simple increment to total

def CalcAverage(guest):
total = 0.0
for key, value in guest.items():
    total += float(value)
return total / len(guest)

print CalcAverage(guest)

You can use The reduce is in the functools in Python 3.0. It is more complex. It accepts an iterator to process, but it's not an iterator itself. It returns a single result

def CalcAverage(guest):
    total = 0.0
    total = reduce(lambda x, y: float(x) + float(y), guest.values())
    return total / len(guest)

print CalcAverage(guest)

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