[英]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.