向用户询问键:值对在Python中

2024-04-18 01:09:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想向用户请求多个键值对并存储它们,以便以后使用它们。我试过几种方法:

columnCombo = {(x for x in input("Enter the Column Name: ")) : (y for y in input("\nEnter the Column Type: "))}

columnCombo = [(x for x in input("Enter the Column Name: ")),(y for y in input("\nEnter the Column Type: "))]

当我把这些打印出来时,我得到:

[<generator object <genexpr> at 0x1019452d0>, <generator object <genexpr> at 0x101945318>]

实际上,我想让用户输入一列的名称,然后输入该列中包含的数据类型。理想情况下,我可以提取名称(字符串)和关联的(类型)


Tags: the用户nameinforinputobjecttype
2条回答
column = {}
print "when done press ctrl+c" 
while True:
    try:
        col_name = input("Enter the Column Name: ")
        col_type = input("Enter the column type: ")
        column[col_name] = col_type
    except KeyboardInterrupt:break

在上面的代码中,它将提示输入unitl用户按键盘中断

column字典上循环

for key in column.keys():
    col_name = key
    col_type = column[key]

可以将这些对象存储在元组中,如下所示:

done = False;
key_value_pairs = []
while not done:
    col_name = input("Enter the Column Name: ")
    if col_name == "":
         done = True
    col_type = input("Enter the Column Type: ")
    if col_type == "":
        done = True

    key_value_pairs.append((col_name, col_type))

一旦你完成了,你可以像这样迭代你的条目:

for key_value_pair in key_value_pairs:
    key = key_value_pair[0]
    value = key_value_pair[1]

相关问题 更多 >

    热门问题