2017-02-20 30 views
0

我发现类似的,几乎相同的问题,但没有一个帮助我。 举例来说,如果我有两个列表:如何查找Python 3中的两个字典列表的交集?

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}] 

你可以看到,在第一个列表中的所有类型的字典具有相同的“A”和第二个关键“B”是在列表中的所有类型的字典一样。我想找到一个字典,其中第一个列表中的关键字'a'和第二个列表中的关键字'b',但是只有当这个字典在这些列表中的一个里面时(在这个例子中,它将是[{'a':1 ,'b':4,'c':139}])。非常感谢:)

+0

什么是对C的条件:139输出进来吗?我可以看到它在任何一个列表中都没有重复。 –

+0

这只是随机数 –

+1

所以'[{'a':1,'b':4,'c':149}]'是你的问题的有效输出吗? –

回答

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 
+0

你是天才兄弟...非常感谢你:) –

0

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

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) 

打印{'a': 1, 'b': 4, 'c': 139}

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) 
相关问题