不会让我找到字典的平均值

Won't let me find average of the dictionary

我需要根据用户输入的内容创建字典。然后我需要让他们输入我已经成功管理的名称和时间长度。我还认为我可以正确地告诉我最短和最长的长度。但是,出于某种原因,它不会让我计算平均值。我花了几个小时在 youtube 上研究它并尝试了不同的东西,所以我的假设是我的代码顶部有些地方不正确,不允许计算平均值。

n = int(input())
my_dict = {}


for i in range(n):
    titles=input("What is the ")
    length=input("What is length?")
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)


shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")


average = sum(my_dict.values())/ len(v)


print("Your average length is", average)

Python 中的输入存储为字符串。更改注释行,您就可以开始了。编辑:如果时间值也包含 floats 那么您也可以将行 length=int(input("What is length?")) 更改为 length=float(input("What is length?"))

n = int(input())
my_dict = {}


for i in range(n):
    titles=input("What is the ")
    length=int(input("What is length?")) # You were taking the input of length as a string. 
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)


shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")


average = sum(my_dict.values())/ len(my_dict)


print("Your average length is", average)

我改变了计算总和的逻辑。现在正在运行。

n = int(input())
my_dict = {}


for i in range(n):
    titles=input("What is the ")
    length=input("What is length?")
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)


shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

sum = 0
for value in my_dict.values():
    sum = sum + int(value)

average = sum/ len(my_dict.values())


print("Your average length is", average)

如果您不想更改输入类型
你可以将字典值更改为 float
喜欢:

n = int(input())
my_dict = {}


for i in range(n):
    titles=input("What is the ")
    length=int(input("What is length?"))  
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)


shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest," minutes long.")
print("Your longest video is", longest," minutes long.")


for v in my_dict.keys():
    my_dict[v] = float(my_dict[v])

avg = sum(my_dict.values()) / len(my_dict)
print (avg)```