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