Comparing Dictionary Lists

I have two lists of test results. The test results are presented in the form of dictionaries:

list1 = [{testclass='classname', testname='testname', testtime='...},...]
list2 = [{testclass='classname', testname='testname', ...},...]

In both lists, the presentation of the dictionary is slightly different, because for one list I have a little more information. But in all cases, each test dictionary in any list will have a class name and the element name testname, which together form a way to uniquely identify the test and a way to compare it in lists.

I need to find out all the tests that are in list1 but not in list2, as they represent new testing failures.

To do this, I:

def get_new_failures(list1, list2):
    new_failures = []
    for test1 in list1:
        for test2 in list2:
            if test1['classname'] == test2['classname'] and \
                    test1['testname'] == test2['testname']:
                break; # Not new breakout of inner loop
        # Doesn't match anything must be new
        new_failures.append(test1);
    return new_failures;

, python. . , , . , , . .

,

.

+5
3

:

def get_new_failures(list1, list2):
    check = set([(d['classname'], d['testname']) for d in list2])
    return [d for d in list1 if (d['classname'], d['testname']) not in check]
+8

classname testname , . : (classname, testname). if (classname, testname) in d: ....

Python 2.7 , OrderedDict collections.

:

tests1 = {('classname', 'testname'):{'testclass':'classname', 
                                     'testname':'testname',...}, 
         ...}
tests2 = {('classname', 'testname'):{'testclass':'classname', 
                                     'testname':'testname',...}, 
         ...}

new_failures = [t for t in tests1 if t not in tests2]

- , list2, , :

test1_tuples = ((d['classname'], d['testname']) for d in test1)
test2_tuples = set((d['classname'], d['testname']) for d in test2)
new_failures = [t for t in test1_tuples if t not in test2_tuples]
+2

To compare two dict d1and d2with a subset of their keys, use:

all(d1[k] == d2[k] for k in ('testclass', 'testname'))

And if your two lists are the same length, you can use zip()to pair them.

+2
source

All Articles