Python搜索特定条目

问题描述:

所以我有代码;Python搜索特定条目

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

要通过这个数据搜索:

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

我如何可以改变它,所以我可以一个变量之前在程序设置为2,使代码只搜索的2名?

+0

你根本不在寻找。 – frederick99

假设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”,并返回两个。 –