在字典中搜索

尼玛高达

我在列表中有一组词典,我需要消除那些包含特定单词的词典并将其他词典返回到列表中。

P = {u'data': 
[{u'data': [{u'paths': u'paths-117', u'endpoint': u'NorthBoundPC', u'cep': u'00:00:0C:9G:2F:FA', u'epg': u'dmzInternet', u'pod': u'pod-1', u'_id': u'5c7616a4b52af58fc536eb1b', u'tenant': u'dmz', u'extpaths': None}, 
 {u'paths': u'paths-117', u'endpoint': u'RR-az1VPC', u'cep': u'00:00:0D:9F:1B:FB', u'epg': u'dmzTransit', u'pod': u'pod-1', u'_id': u'5c7616a4b52af58fc536eb15', u'tenant': u'dmz', u'extpaths': None}, 
 {u'paths': u'paths-127', u'endpoint': u'eth1/4', u'cep': u'00:09:6G:6C:6B:E2', u'epg': u'App', u'pod': u'pod-1', u'_id': u'5c7616a3b52af58fc536d710', u'tenant': u'CRL', u'extpaths': None}]}

我在其中使用 FOR 循环和 IF 来匹配字符RR逻辑是如果RR存在endpoint则忽略它。例如在第二本字典中它的存在。

hosts = []
for record in P:           
    if record["endpoint"] and  "RR" not in record["endpoint"]:
        hosts.append(record)
return hosts

它抛出以下错误:

TypeError: string indices must be integers
暮光之城

首先,您P的无效,您需要]}在最后补充

P = {u'data': 
[{u'data': [{u'paths': u'paths-117', u'endpoint': u'NorthBoundPC', u'cep': u'00:00:0C:9G:2F:FA', u'epg': u'dmzInternet', u'pod': u'pod-1', u'_id': u'5c7616a4b52af58fc536eb1b', u'tenant': u'dmz', u'extpaths': None}, 
 {u'paths': u'paths-117', u'endpoint': u'RR-az1VPC', u'cep': u'00:00:0D:9F:1B:FB', u'epg': u'dmzTransit', u'pod': u'pod-1', u'_id': u'5c7616a4b52af58fc536eb15', u'tenant': u'dmz', u'extpaths': None}, 
 {u'paths': u'paths-127', u'endpoint': u'eth1/4', u'cep': u'00:09:6G:6C:6B:E2', u'epg': u'App', u'pod': u'pod-1', u'_id': u'5c7616a3b52af58fc536d710', u'tenant': u'CRL', u'extpaths': None}]}]}

因此,您有一个带有(一个)字符串键 ( data) 和一个字典列表作为值的字典。该列表只有一个元素,同样是一个带有字典列表的字典(多么奇怪的数据结构,您应该尝试简化该结构):

[{u'data': [{u'paths': u'paths-117', u'endpoint': u'NorthBoundPC', u'cep': 
 u'00:00:0C:9G:2F:FA', u'epg': u'dmzInternet', u'pod': u'pod-1', u'_id': 
 u'5c7616a4b52af58fc536eb1b', u'tenant': u'dmz', u'extpaths': None}, {u'paths': 
 u'paths-117', u'endpoint': u'RR-az1VPC', u'cep': u'00:00:0D:9F:1B:FB', u'epg': 
 u'dmzTransit', u'pod': u'pod-1', u'_id': u'5c7616a4b52af58fc536eb15', u'tenant':    
 u'dmz', u'extpaths': None}, {u'paths': u'paths-127', u'endpoint': u'eth1/4',     
 u'cep': u'00:09:6G:6C:6B:E2', u'epg': u'App', u'pod': u'pod-1', u'_id': 
 u'5c7616a3b52af58fc536d710', u'tenant': u'CRL', u'extpaths': None}]}]

该列表中有三本词典。那就是您要过滤的列表!因此,查看您的代码,我们看到 afor record in P:for record in P.keys():. 通过检查您的数据结构,很明显这还不够循环。

我们需要循环三遍才能到达我们想要的位置:

hosts = []
for k in P:
 for outerlist in P[k]:
  for record in outerlist[kk]:
   if "RR" not in record.get("endpoint", ""):
    hosts.append(record)

我还缩短了if使用get.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章