2013-08-29 22 views
0

所以我有一個由數字組成的字典,它的定義是元素週期表中的相應元素。如何從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',則程序會顯示「這不是元素!」。爲什麼是這個,我該如何解決它?

在此先感謝

+2

如果他們進入Ununoctium而不是會發生什麼? – doctorlove

+0

是否有大寫字母的問題?嘗試'line.lower()'以確保用戶輸入全部爲小寫。 (和'value.lower()'爲測試的另一邊) – Bonlenfum

+0

你可以使用pprint.pprint(the_dictionary)來手動檢查你的代碼中有什麼 –

回答

2

這是很容易有蟒蛇做的查找你。忽略空行現在:

elements = [] 
for line in open("periodic_table.txt"): 
    elements.append(line[3:]) 

然後,您可以做一個查詢這樣的:

if answer.isdigit(): 
    print elements[int(answer)] 
else: 
    print elements.index(answer) 
2

我懷疑這是一個區分大小寫的問題。
更改

if line == value: 

if line.lower() == value.lower(): 

會解決這個問題。
雖然你在那裏,但爲什麼for循環內的if? 你可以檢查,然後再不需要break

if line.isdigit(): 
    if int(line) <= 118 and int(line) > 0: 
     print ("Element number",line, "is",elements[int(line)]) 
     check = 1 
     #<-------- break no longer required 
else: 
    #for loop as above 
+0

我做了一些改變,我很確定它不是一個區分大小寫問題。 –

+0

「一些更改」==這些更改? – doctorlove

+0

是的,你上面提出的改變,但這不是問題,我已經解決了它!問題在於,當程序構建字典時,它在具有3位數字的元素前面添加了空格,並且由於用戶在輸入元素名稱時沒有輸入空格,程序會將其視爲不正確,因此將其聲明爲「不是元素」。 –

相關問題