在具有不同键的两个字典列表之间查找相同的值

2024-04-30 06:00:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个字典列表:

list_1 = [{a:'cat', b:'dog', c:'bird'},{a:'**mouse**', b:'lizard', c:'fish'},{a:'**hen**', b:'pony', c:'frog'}]
list_2 = [{x:'goat', y:'**mouse**', z:'horse'},{x:'horse', y:'**hen**', z:'tiger'},{x:'bee', y:'fly', z:'toad'}]

值“mouse”和值“hen”出现在两个字典列表中,但这两个值都有唯一的键

在本例中,当两个列表中的“mouse”键和“hen”键不同时,如何查找列表_1和列表_2之间字典值的匹配位置

我试图搜索类似的帖子,但只找到了匹配键的比较。 (示例:在两个列表中,“hen”的键为“a”,而“鼠标”的值为“c”)


Tags: 列表字典listcatponytigerdoghen
2条回答

我制作了一个函数来获取dict列表的所有唯一值

def unique_values_from_list(dict_list):
    all_values = set()
    for dictionary in dict_list:
        all_values.update(dictionary.values())
    return all_values

使用此代码,我们可以获得两组唯一值,并找到这两组值的交点:

list_1 = [{'a':'cat', 'b':'dog', 'c':'bird'},{'a':'mouse', 'b':'lizard', 'c':'fish'},{'a':'hen', 'b':'pony', 'c':'frog'}]
list_2 = [{'x':'goat', 'y':'mouse', 'z':'horse'},{'x':'horse', 'y':'hen', 'z':'tiger'},{'x':'bee', 'y':'fly', 'z':'toad'}]

unique1 = unique_values_from_list(list_1)
unique2 = unique_values_from_list(list_2)

print(unique1)
print(unique2)
intersection = unique1.intersection(unique2)
print(intersection)

我的结果是:

unique1: {'fish', 'cat', 'frog', 'dog', 'lizard', 'hen', 'pony', 'bird', 'mouse'}
unqiue2: {'goat', 'fly', 'horse', 'hen', 'toad', 'mouse', 'tiger', 'bee'}
intersection: {'hen', 'mouse'}
def get_values(list_of_dict):
    a = set()
    for a_dict in list_of_dict:
        a.update(a_dict.values())
    return a

print(get_values(listA).intersection(get_values(listB)))

也许吧

相关问题 更多 >