2016-08-03 56 views
1

我通過檢索json格式的數據在python中創建了一本字典。無法在字典中使用python腳本輸入字符

[{"id":"1","kingdom":"Metazoa ","phylum":"Arthropoda ","class":"Insecta ","order":"Hemiptera ","family":"Belostomatidae ","genus":"Abedus"},<br> 
{"id":"2","kingdom":"Viridiplantae ","phylum":"Streptophyta ","class":"unclassified_Streptophyta ","order":"Pinales ","family":"Pinaceae ","genus":"Abies"}] 

當我訪問這些數據,我想只拿這樣的,其中的genus值爲Abies,而是我得到的錯誤

ValueError : invalid literal for int () with base 10 : 'Abies'

但是,如果我輸入一個數值,我得到的數據對應於json的「id」。

這是我的腳本:

import urllib2 
import simplejson 

title = raw_input("find taxonom: ") 
print "key: ",title 

response = urllib2.urlopen("http://localhost/csv/taxo.json") 
data = simplejson.load(response) 
get = int(str(title)) 
print data[get] 

我如何得到它顯示的數據「ID」,「王國」,每一個爲屬匹配輸入數據的「phlyum」,「階級」,等等?

+0

'int(str(title))'不能正確:它表示「獲取標題,使其成爲一個字符串,並使該字符串的整數」。我認爲標題不是整數。 – 9000

回答

3

你得到的錯誤是因爲你試圖將包含非數值的字符串轉換爲整數。要解決此問題,請刪除get = int(str(title))


您擁有的數據是一個列表。列表使用數字索引來訪問列表中不同位置的元素。要打印genus值,你要做的:

print data[1]['genus'] 

注意,這個目標在列表中的第二個字典。要打印的genus值第一個字典,你必須改變10


要打印其中包含genus匹配標題值每個字典的值,這樣做:

for attr_map in data: 
    if attr_map['genus'] == title: 
     print attr_map 

程序的運行示例:

>>> import json 
>>> buffer = '[{"id":"1","kingdom":"Metazoa ","phylum":"Arthropoda ","class":"Insecta ","order":"Hemiptera ","family":"Belostomatidae ","genus":"Abedus"},{"id":"2","kingdom":"Viridiplantae ","phylum":"Streptophyta ","class":"unclassified_Streptophyta ","order":"Pinales ","family":"Pinaceae ","genus":"Abies"}]' 
>>> data = json.loads(buffer) 
>>> data 
[{u'kingdom': u'Metazoa ', u'family': u'Belostomatidae ', u'class': u'Insecta ', u'id': u'1', u'phylum': u'Arthropoda ', u'genus': u'Abedus', u'order': u'Hemiptera '}, {u'kingdom': u'Viridiplantae ', u'family': u'Pinaceae ', u'class': u'unclassified_Streptophyta ', u'id': u'2', u'phylum': u'Streptophyta ', u'genus': u'Abies', u'order': u'Pinales '}] 
>>> 
>>> title = raw_input("find taxonom: ") 
find taxonom: Abies 
>>> for attr_map in data: 
...  if attr_map['genus'] == title: 
...   print attr_map 
... 
{u'kingdom': u'Viridiplantae ', u'family': u'Pinaceae ', u'class': u'unclassified_Streptophyta ', u'id': u'2', u'phylum': u'Streptophyta ', u'genus': u'Abies', u'order': u'Pinales '} 
+1

可能,不是OP想要的。他希望通過'genus'鍵進行搜索。 – SuperSaiyan

+1

謝謝@SuperSaiyan,是的,我想找到關鍵詞屬。 –

+0

謝謝@ smac89,如果我刪除'get = int(str(title))'有一個錯誤'TypeError:列表索引必須是整數,而不是str' –

2

這將找到相匹配的第一個條目:

print next(x for x in data if x["genus"] == title) 
+0

如果你打算使用'next'而不是'[<列表理解>] [0]',爲什麼不只是'下一個()'? – jedwards

+1

當我寫下'next'時,忘記取下它們。現在修復它。感謝您指出! – SuperSaiyan

+0

@SuperSaiyan不能工作錯誤'StopIteration' –