简体   繁体   English

编写一个程序,使用循环从用户那里获取 3 个键值输入,并使用这些键和值创建一个字典

[英]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.

相关问题 更新字典并使用循环值创建键值对 - Update dictionary and create key-value pairs with loop values 如何使用(相同长度和相同键)两个不同字典的值创建一个新字典,用作键值对 - How to make a new dictionary from the values of (same lengths and same keys) two different dictionaries, using as key-value pair 如何从列表中创建一个字典,只包含键列表和键值对(Python)? - How to create a dictionary from a list with a list of keys only and key-value pairs (Python)? 根据来自单独列表的匹配项,使用来自字典列表中的值的键值对创建一个新字典 - Create a new dictionary with the key-value pair from values in a list of dictionaries based on matches from a separate list Python:如何匹配键,然后将键值对值的值与另一个字典中的值相乘? - Python: How do I match keys then multiply the values of a key-value pair value with values from another dictionary? 如何使用 while 循环从用户输入中附加具有任意数量的键和多个值的字典 - How can I use a while loop to append a dictionary with an arbitrary number of keys and multiple values from user inputs 交换字典键和值仅适用于 3 个键值对字典 - Swapping dictionary keys and values works only on 3 key-value pair dictionary 使用字典中的键值翻译字符串 - translating a string using key-value from dictionary 在不使用 for 循环的情况下基于键值对创建字典 - Create a dict based on key-value pairs without using a for loop 如何根据具有重复键值对的数据帧行将值附加到 python 字典中的键 - How to append values to keys in python dictionary based on dataframe rows with repeated key-value pairs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM