[英]I'm having trouble with dictionaries in python
我正在用Python
编写代码。 我已经定义了很多字典和一个 function。 我使用 function 中的字典。 字典名称是 function 中的参数。 我想获取用户输入要使用的字典,但我不知道该怎么做。 我试图用下面代码行中的名称获取字典的名称,但没有
name=input()
bank("name")
error is:
Traceback (most recent call last):
File "............", line 47, in <module>
banka("hesap")
File "...................", line 18, in banka
print("merhaba",hesap['ad'])
TypeError: string indices must be integers
这是您代码的这一部分:
hesap['ad']
根据错误, hasep
是一个字符串,而不是字典。 所以你只能将整数放入方括号中。
你也许可以做这样的事情
dictionary1 = {}
dictionary2 = {}
user_input = input("Enter 'dictionary1' for dictionary 1 or enter 'dictionary2' for dictionary 2")
if user_input == "dictionary1":
bank(user_input)
elif user_input == "dictionary2":
bank(user_input)
else:
print("unknown command")
同样对于您的代码,当您使用银行 function 时,您将变量“名称”放在语音标记中。 如果要在 function 库中输入变量名,不要添加语音标记。 :)
也许尝试这样做:
dict1={...}
dict2={...}
def bank(x):
if x=="dict1":
usedict=dict1
elif x=="dict2":
usedict=dict2
else:
print("No dictionary found with input given")
## write your program using usedict
x=input("enter which dictionary to use")
bank(x)
请记住,如果您还想在 function 之外使用字典 usedict,请在 function 内使用全局 usedict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.