-2

Write a program that will prompt the user for a series of names and ages. (Use the fake name End to mark the end of the sequence of values.) After the values have been entered, print the average age, and the last names and ages of those individuals with the highest and lowest age.

I have code that will produce an average, oldest, and youngest age but without the corresponding name. I have no idea how to make it work from user input. I am using the latest version of Python and the IDE PyCharm.

#name = input("Enter a series of names with corresponding ages:")

name = ["john", 25, "james", 32, "tanner", 62, "laura", 41, "christine", 21]
pairs = dict([tuple(name[i:i+2]) for i in range(0, len(name), 2)])

avg_salary = sum(pairs.values()) / len(pairs)
print("Average Age: %f" % (avg_age))

high_age = max(pairs.values())
print("Highest Age: %f" % (high_age))

low_age = min(pairs.values())
print("Lowest Age of: %f" % (low_age))
Roqux
  • 608
  • 1
  • 11
  • 25
MJL
  • 1
  • 1

1 Answers1

0

If you are using Python3, you can use items() method on dict

#name = input("Enter a series of names with corresponding ages:")

import numpy as np

name = ["john", 25, "james", 32, "tanner", 62, "laura", 41, "christine", 21]
pairs = dict([tuple(name[i:i+2]) for i in range(0, len(name), 2)])

avg_age = np.mean(pairs.values())
print("Average Age: %.2f" % (avg_age))

high_age = max(pairs.items())
print("Highest Age: %i" % (high_age[1]) + " and their name is " + high_age[0])

low_age = min(pairs.items())
print("Lowest Age: %i" % (low_age[1]) + " and their name is " + low_age[0])

Result:

Average Age: 36.20
Highest Age: 62 and their name is tanner
Lowest Age: 21 and their name is christine

If you are using Python 2, then this question might be of some interest to you: What is the difference between dict.items() and dict.iteritems()? especially the first answer (accepted answer)

ggrelet
  • 1,071
  • 7
  • 22