簡體   English   中英

根據鍵和值列表搜索字典列表

[英]Search list of dictionaries based on the key and list of values

給定以下字典:

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

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'

最優化的解決方案可能是一個非常危險的問題。 以下代碼段可能會相當快地獲得您的結果,但請注意它不考慮重復值。 如果您正在尋找“最佳”解決方案,您可能希望非常確定您的上下文並適合您的解決方案。

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM