[英]Write a program that uses a loop to take 3 key-value inputs from the user and create a dictionary using these keys and values
I'm very new to learning programming.我对学习编程很陌生。 I'm starting with Python. Do you know the solution to this problem?我从 Python 开始。你知道这个问题的解决方案吗? That's the closest output I can get...那是我能得到的最接近的 output...
My attempt:我的尝试:
my_dict={}
for items in range(1,4):
key=str(input('enter string'))
value=int(input('enter #'))
my_dict={f'{key}: {value}'}
print(my_dict)
output: output:
{'gregory: 34'}
{'perry: 84'}
{'sinatra: 76'}
Expected Output:预计 Output:
{'gregory': '34', 'perry': '84', 'sinatra': '76'}
I don't know how to get everything on the same line...我不知道如何让所有东西都在同一条线上......
my_dict={f'{key}: {value}'}
This creates a brand new dictionary, because you're reassigning the name my_dict
.这将创建一个全新的字典,因为您正在重新分配名称my_dict
。
You don't want this;你不想要这个; you want to add this key-value pair to the existing dictionary.您想将此键值对添加到现有字典中。
Use this instead:改用这个:
my_dict[key] = value
And then move the print statatement below the loop.然后将打印语句移至循环下方。
Oh, I see: Thanks for your help!哦,我明白了:谢谢你的帮助! :) :)
my_dict={}
for items in range(1,4):
key=str(input('enter string'))
value=str(input('enter #'))
my_dict[key]=value
print(my_dict)
It worked.有效。 yay!好极了! I also had to make both variables strings to get the quotation marks.我还必须制作两个变量字符串以获得引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.