基于键和值列表的字典搜索列表

时间:2021-03-29 21:36:14

标签: python list dictionary

给定以下字典:

recs = [
    {'id': 1,
     'custom': {
         {'tag': 'A'},
         {'tag': 'B'},
         {'tag': 'C'},
         {'name': 'Max'}

     }
     },

    {'id': 2,
     'custom': {
         {'tag': 'A'},
         {'tag': 'C'},
         {'note': 'Note for 2'}

     }
     },

    {'id': 3,
     'custom': {
         {'tag': 'B'},
         {'tag': 'C'},
         {'value': 12}
     }
     },

    {'id': 4,
     'custom': {
         {'tag': 'A'},
         {'tag': 'B'},
         {'tag': 'C'}
     }
     }
]

理想情况下,在没有 Pandas 等附加模块的情况下,按标签列表进行搜索的最佳解决方案是什么。

例如:tag == [A, B, C] 会返回

id=1 和 id=4

2 个答案:

答案 0 :(得分:0)

taglist_dictionnary = {}
for item in recs :
  for key in item.keys() :
    if key == 'id':
      id = item[key]
      print(id)
    if key == 'custom':
      taglist = []
      tagdict = item[key]
      for tagkey in tagdict.keys() :
        if tagkey == 'tag':
          taglist.append(tagdict[tagkey])
      taglist_dictionnary.update({id : taglist})

print(taglist_dictionnary)

这会给你类似的东西:

{'1':[A,B,C], '2',[A,C] ... }

等等。那么检查每个键列表中标签的存在可能是一种更有用的架构?

但实际上,您的字典不起作用,因为它是不可哈希的。请参阅此线程:TypeError: unhashable type: 'dict'

答案 1 :(得分:0)

最佳解决方案可能是一个非常危险的问题。以下代码段可能会相当快地获得您的结果,但请注意它不会考虑重复值。如果您正在寻找“最优化”的解决方案,您可能希望非常确定您的上下文,并使您的解决方案与之相适应。

values_to_check = ['A', 'B', 'C']
num_values = len(values_to_check)

def check_dict(d, vtc):
    return [v for v in vtc if v in d['custom'].values()]

ids = [d['id'] for d in recs if len(check_dict(d, values_to_check)) == num_values]