所以我有一個由數字組成的字典,它的定義是元素週期表中的相應元素。如何從Python中的字典中調用項目?
我已經建立了字典是這樣的:
for line in open("periodic_table.txt"):
temp.append(line.rstrip())
for t in temp:
if t[1] != " ":
elements[x] = t[3:]
else:
elements[x] = t[2:]
x += 1
我知道,每一個元素是表,因爲我讓程序打印字典。 這樣做的一點是,用戶輸入一個號碼或元素名稱和編號和名稱都被打印:
while count == 0:
check = 0
line = input("Enter element number or element name: ")
if line == "":
count = count + 1
break
for key,value in elements.items():
if line == value:
print ("Element number for",line,"is",key)
check = 1
break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
break
if check == 0:
print ("That's not an element!")
這適用於每個元素除了最後一個,Ununoctium,在字典中。當用戶輸入118時,打印此元素,但如果他們輸入'ununoctium',則程序會顯示「這不是元素!」。爲什麼是這個,我該如何解決它?
在此先感謝
如果他們進入Ununoctium而不是會發生什麼? – doctorlove
是否有大寫字母的問題?嘗試'line.lower()'以確保用戶輸入全部爲小寫。 (和'value.lower()'爲測試的另一邊) – Bonlenfum
你可以使用pprint.pprint(the_dictionary)來手動檢查你的代碼中有什麼 –