2017-03-01 128 views
0

所以我有代碼;Python搜索特定條目

names= [index + " - " + js[index]["name"] for index in js] 

要通過這個數據搜索:

{ "1": {"name":"One"} }, 
{ "2": {"name":"Two"} }, 
{ "3": {"name":"Three"} }, 

我如何可以改變它,所以我可以一個變量之前在程序設置爲2,使代碼只搜索的2名?

+0

你根本不在尋找。 – frederick99

回答

0

假設JS是一個有效的字典:

js = { "1": {"name":"One"}, 
     "2": {"name":"Two"}, 
     "3": {"name":"Three"}} 

你是建設有「名」的所有值的列表。如果你只希望這些指標,其中「名」等於「二」,它包含在列表理解:

>>> needle = "Two" 
>>> names = ["{} - {}".format(index, js[index]["name"]) for index in js if js[index]["name"]==needle] 

>>> print(names) 
['2 - Two'] 

編輯:關於你的評論,如果你嘗試獲得數值「2」爲「2」鍵,您可以直接訪問字典的常用方法:

>>> needle="2" 
>>> js[needle]["name"] 
'Two' 

在這個特定的,簡化的情況下,它會更容易地使用平板詞典:

js = { "1": "One", 
     "2": "Two", 
     "3": "Three"} 

訪問(「搜索」)然後將是:

>>> js[needle] 
'Two' 
+0

謝謝,這很有幫助。其實我試圖問如何搜索「2」,並返回兩個。 –