[英]Python filter a list of dictionaries by another dictionary values
I have the below list of dictionaries & a dictionary, I want to return the person name if there's a match我有以下字典列表和字典,如果有匹配项,我想返回人名
mydblist = [{'name': 'Alice', 'AGATC': '2', 'AATG': '8', 'TATC': '3'},{'name': 'Bob', 'AGATC': '4', 'AATG': '1', 'TATC': '5'},{'name': 'Charlie', 'AGATC': '3', 'AATG': '2', 'TATC': '5'}]
dna_dict = {'AGATC': 4, 'AATG': 1, 'TATC': 5}
so now I need to print name 'Bob' from the list of dictionaries mydict_list, as he has a full match with dna_dict,所以现在我需要从字典列表 mydict_list 中打印名称“Bob”,因为他与 dna_dict 完全匹配,
or print no match in case no match found或打印 no match 以防找不到匹配项
Many thanks for your support in advance非常感谢您的提前支持
Using the list provided I wrote the solution below.使用提供的列表,我在下面编写了解决方案。 It's just compare the dict keys.
它只是比较字典键。 One dict has a str type and other with int type that's why the code convert the type.
一个 dict 具有 str 类型,另一个具有 int 类型,这就是代码转换类型的原因。
def compare_dicts(a, b):
"""
Compare all keys of A with the same key in B
"""
for key in a.keys():
if key in b:
if a[key] != int(b[key]):
return False
return True
for dict_obj in mydblist:
if compare_dicts(dna_dict, dict_obj):
print(dict_obj['name'])
Try it试试看
mydblist = [{'name': 'Alice', 'AGATC': '2', 'AATG': '8', 'TATC': '3'},{'name': 'Bob', 'AGATC': '4', 'AATG': '1', 'TATC': '5'},{'name': 'Charlie', 'AGATC': '3', 'AATG': '2', 'TATC': '5'}]
# Here i changed dna_dict value integer to string
dna_dict = {'AGATC': '4', 'AATG': '1', 'TATC': '5'}
for i in mydblist:
if i["AGATC"] == dna_dict["AGATC"] and i["AATG"] == dna_dict["AATG"] and i["TATC"] == dna_dict["TATC"]:
print(i["name"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.