繁体   English   中英

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

[英]Find same values between 2 list of dictionaries with different keys

我有两个字典列表:

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' 出现在两个字典列表中,但两个值都有唯一的键。

在此示例中,当两个列表中“鼠标”的键和“母鸡”的键不同时,如何找到字典值在 list_1 和 list_2 之间匹配的位置?

我试图搜索类似的帖子,但只找到了使用匹配键完成的比较。 (例如:在两个列表中,'hen' 的键为 'a','mouse' 的值为 'c')

我做了一个函数来获取字典列表的所有唯一值。

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)))

也许?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM