2017-02-20 3 views
0

Ich habe ähnliche, fast gleiche Fragen gefunden, aber keine davon hat mir geholfen. Zum Beispiel, wenn ich zwei Listen haben:Wie findet man den Schnittpunkt zweier Wörterbücher in 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}] 

Sie können in der ersten Liste sehen, dass alle dicts gleichen ‚a‘ haben und in der zweiten die Taste ‚b‘ ist in allen dicts in der Liste gleich. Ich möchte ein Wörterbuch finden, das den Schlüssel 'a' von der ersten Liste und den Schlüssel 'b' von der zweiten Liste hat, aber nur wenn dieses Wörterbuch in einer dieser Listen ist (in diesem Beispiel wäre es [{'a': 1 , 'b': 4, 'c': 139}]). Vielen Dank im Voraus :)

+0

was die Bedingung für c: 139 Ausgang zu kommen? Ich kann sehen, dass es sich in keiner der Listen wiederholt. –

+0

Es ist nur Zufallszahl –

+1

so '[{'a': 1, 'b': 4, 'c': 149}]' wäre eine gültige Ausgabe für Ihre Frage? –

Antwort

0

Nicht besonders attraktiv, aber macht den Trick.

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

Sie sind Genie Bro ... Vielen Dank :) –

0

Diese Lösung funktioniert mit allen Tasten:

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) 

Drucke {'a': 1, 'b': 4, 'c': 139}

0

Das vielleicht:

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