2017-02-20 127 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)