如何在Python 3中找到两个字典列表的交集?

时间:2017-02-20 18:18:53

标签: python list dictionary

我发现了类似的,几乎相同的问题,但这些都没有帮助我。 例如,如果我有两个列表:

list1 = [{'a':1,'b':2,'c':3},{'a':1, 'b':5, 'c':6}]
list2 = [{'a':2,'b':4,'c':9},{'a':1, 'b':4, 'c':139}]

您可以看到,在第一个列表中,所有dicts都具有相同的“a”,在第二个列表中,所有dicts中的键“b”相同。我想找到一个字典,其中第一个列表中的键为“a”,第二个列表中的键为“b”,但只有当该字典位于其中一个列表中时(在此示例中,它将是[{'a':1} ,'b':4,'c':139}])。非常感谢提前:)

3 个答案:

答案 0 :(得分:0)

不是特别有吸引力,但有诀窍。

list1 = [{'a':1,'b':2,'c':3},{'a':1, 'b':5, 'c':6}]
list2 = [{'a':2,'b':4,'c':9},{'a':1, 'b':4, 'c':139}]

newdict = {} #the dictionary with appropriate 'a' and 'b' values that you will then search for

#get 'a' value
if list1[0]['a']==list1[1]['a']:
    newdict['a'] = list1[0]['a']
#get 'b' value
if list2[0]['b']==list2[1]['b']:
    newdict['b'] = list2[0]['b']

#just in case 'a' and 'b' are not in list1 and list2, respectively
if len(newdict)!=2:
    return

#find if a dictionary that matches newdict in list1 or list2, if it exists
for dict in list1+list2:
    matches = True #assume the dictionaries 'a' and 'b' values match

    for item in newdict: #run through 'a' and 'b'
        if item not in dict:
            matches = False
        else:
            if dict[item]!=newdict[item]:
                matches = False
    if matches:
        print(dict)
        return

答案 1 :(得分:0)

此解决方案适用于任何键:

$HOME

打印def key_same_in_all_dict(dict_list): same_value = None same_value_key = None for key, value in dict_list[0].items(): if all(d[key] == value for d in dict_list): same_value = value same_value_key = key break return same_value, same_value_key list1 = [{'a':1,'b':2,'c':3},{'a':1, 'b':5, 'c':6}] list2 = [{'a':2,'b':4,'c':9},{'a':1, 'b':4, 'c':139}] list1value, list1key = key_same_in_all_dict(list1) list2value, list2key = key_same_in_all_dict(list2) for dictionary in list1 + list2: if list1key in dictionary and dictionary[list1key] == list1value and list2key in dictionary and dictionary[list2key] == list2value: print(dictionary)

答案 2 :(得分:0)

这可能是:

your_a = list1[0]['a'] # will give 1
your_b = list2[0]['b'] # will give 4

answer = next((x for x in list1 + list2 if x['a'] == your_a and x['b'] == your_b), None)