在Python中使用元组作为键

2024-04-26 13:30:12 发布

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

我对编程很陌生,所以请原谅我,如果有什么不合理的地方,或者我用词不正确的话。我有一个关于使用元组作为字典键的问题。在

首先,我让用户输入一个数字

num = input("Enter a number here: ")

然后,我将这个数值转换成一个元组:

^{pr2}$

接下来,我创建一个字典,将数字键与单词值连接起来:

numWords = {'1': "One", '2': "Two", '3': "Three", '4': "Four", '5': "Five", '6': "Six", '7': "Seven", '8': "Eight", '9': "Nine"}

最后,我希望它打印对应于元组中键的字典值。我很肯定这就是我弄错的地方。在

print(numWords[numTup])

基本上,我想用这个程序把每个用户输入的数字打印成一个单词,也就是说,456将变成“四五六”。在

完整(不正确)脚本:

num = input("Enter a number here: ")
numTup = tuple(num)
numWords = {'1': "One", '2': "Two", '3': "Three", '4': "Four", '5': "Five", '6': "Six", '7': "Seven", '8': "Eight", '9': "Nine"}
print(numWords[numTup])

Tags: 用户numberinput字典here地方数字单词
3条回答

dict键的type与用tuple(num)转换为元组后的输入不匹配。 您可以跳过转换为元组的部分:

num = input("Enter number here: ")
num = input("Enter a number here: ")
numWords = {'1': "One", '2': "Two", '3': "Three", '4': "Four", '5': "Five", '6': "Six", '7': "Seven", '8': "Eight", '9': "Nine"}
print(numWords[num])

或者

索引元组并通过选取第0个元素来访问元素:

^{pr2}$

注意:确保键的数据类型和用于访问dict项的变量是相同的。您可以使用type()命令检查变量的数据类型。在

'''
You can print the number in words given irs numeric
version if by defining your dictionary with
the following format:
    dict{'number': 'word'}

Then, calling the dictionary as follows:
    dict['number']
'''

# Number (keys) and words (values) dictionary
numWords = {'1': "One", '2': "Two", 
'3': "Three", '4': "Four", 
'5': "Five", '6': "Six", 
'7': "Seven", '8': "Eight", 
'9': "Nine", '10': "Ten"}

# Function that prints the number in words
def print_values():
    for k,v in numWords.items():
        print(v)

'''
Alternatively, if you want to print a value using
its key as an argument, you can use the following
funciton:
'''

# Interactive function to print number in words
# given the number
def print_values2():
    key = input("What number would you like to print? ")
    print(numWords[key])

'''
P.s. if you want to add a number to your dictionary
you can use the following function
'''

# Function to modify numWords
def add_number():

    # Specify the number you want to add
    numeric = input("Type in the number: ")

    # Input the number in words
    word = input("Write the number in words: ")

    # Assign number and word to dictionary
    numWords[numeric] = word

    # Return modified dictionary
    return numWords

在这种情况下,tuple是不必要的,因为您的字典将处理将键分配给相关字符串的问题。在

num = input("Enter a number here: ")

numWords = {'1': "One", '2': "Two", '3': "Three", '4': "Four", '5': "Five", '6': "Six", '7': "Seven", '8': "Eight", '9': "Nine"}
for n in num:
    print(numWords[n], end=' ')

演示:

^{pr2}$

相关问题 更多 >