Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:按给定键在字典数组中搜索_Python_Json_List - Fatal编程技术网

Python:按给定键在字典数组中搜索

Python:按给定键在字典数组中搜索,python,json,list,Python,Json,List,我有一个字典数组d,通过解析JSON文件获得:d=r.JSON 假设d包含 d = [ {'change':'112','end_time':'2020-05-12','hostname':'a,b,c,d,e','ref':'345','start_time':'202-04-2020'}, {'change':'182','end_time':'2020-05-12','hostname':'a1,b1,c1,d1,e1','ref':'325','start_time':'202-

我有一个字典数组d,通过解析JSON文件获得:d=r.JSON

假设d包含

d = [
  {'change':'112','end_time':'2020-05-12','hostname':'a,b,c,d,e','ref':'345','start_time':'202-04-2020'},
  {'change':'182','end_time':'2020-05-12','hostname':'a1,b1,c1,d1,e1','ref':'325','start_time':'202-04-2020'},
  {'change':'122','end_time':'2020-05-12','hostname':'g,h,i,j,k','ref':'315','start_time':'202-04-2020'},
  {'change':'112','end_time':'2020-05-12','hostname':'o,t1,h1,e4,n7','ref':'345','start_time':'202-04-2020'},
]
如果所有主机名彼此不同,那么如何执行类似的搜索

if hostname=='a1':
  print change (i.e 182)

首先,您有很多json结构错误:

d=[{'change':'112','end_time':'2020-05-12','hostname':'a,b,c,d,e','ref':'345','start_time':'202-04-2020'},
{'change':'182','end_time':'2020-05-12','hostname':'a1,b1,c1,d1,e1','ref':'325','start_time':'202-04-2020'},
{'change':'122','end_time':'2020-05-12','hostname':'g,h,i,j,k','ref':'315','start_time':'202-04-2020'},
{'change':'112','end_time':'2020-05-12','hostname':'o,t1,h1,e4,n7','ref':'345','start_time':'202-04-2020'}]


 hostname='a1'
 for row in d:
   arr = row['hostname'].split(",")
   if hostname in arr:
     print(row['change'])




 #parse all the keys for learning.
  for row in d:
     for k in row.keys():
         if k == "hostname":
             arr = row[k].split(",")
             for s in arr:
                 #print(s)
                 if s =='a1':
                     row['change'] = '777'

print(d)
之后,使用reverse重新排列json中的元组。
玩得开心

您需要遍历该列表,将主机名拆分为一个列表,并检查您正在搜索的主机名是否存在于该列表中

hostname = 'a1'
for row in d:
  hostnames = row['hostname'].split(',')
  if hostname in hostnames:
    print(row['change'])

用理解来解决这个问题的python方法也是最简单的

# for your a1 example
change_a1 = [i['change'] for i in d
             if 'a1' in i['hostname']]
对于任意搜索,只需将其包装为函数

def find_change(host):
    change = [i['change'] for i in d
              if host in i['hostname']]
    return change

请显示并格式化您的代码-您尝试了什么?你知道如何循环浏览列表吗?比较价值观?请阅读以下内容:字典的全部意义在于让您能够即时访问任何密钥。你为什么要把所有的钥匙都绕过去?你有赖特!我很匆忙,没有把书读清楚。。我会更新。