简体   繁体   English

我在使用 python 中的字典时遇到问题

[英]I'm having trouble with dictionaries in python

I'm writing code with Python .我正在用Python编写代码。 I have defined a lot of dictionaries and a function.我已经定义了很多字典和一个 function。 I use the dictionary in the function.我使用 function 中的字典。 The dictionary name is the parameter's in function.字典名称是 function 中的参数。 I want to get user input which dictionary to use but I don't know how to do this.我想获取用户输入要使用的字典,但我不知道该怎么做。 I tried to get the name of the dictionary with the name in the code line below but it didn't我试图用下面代码行中的名称获取字典的名称,但没有

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

It's this part of your code:这是您代码的这一部分:

hesap['ad']

According to the error, hasep is a string, not a dictionary.根据错误, hasep是一个字符串,而不是字典。 So you can only put integers into the square brackets.所以你只能将整数放入方括号中。

You could maybe do someting like this你也许可以做这样的事情

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")

Also for your code, when you used the bank function, you put the variable 'name' in speech marks.同样对于您的代码,当您使用银行 function 时,您将变量“名称”放在语音标记中。 If you want to input the variable name in the function bank, dont add speech marks.如果要在 function 库中输入变量名,不要添加语音标记。 :) :)

Maybe try doing this:也许尝试这样做:

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)

Remember, if you want to use the dictionary usedict outside the function as well, use global usedict inside the function请记住,如果您还想在 function 之外使用字典 usedict,请在 function 内使用全局 usedict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM