Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing lists of dictionaries

I have two lists of test results. The test results are represented as dictionaries:

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

The dictionary representation is slightly different in both lists, because for one list I have some more information. But in all cases, every test dictionary in either list will have a classname and testname element which together effectively form a way of uniquely identifying the test and a way to compare it across lists.

I need to figure out all the tests that are in list1 but not in list2, as these represent new test failures.

To do this I do:

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;

I am wondering is a more python way of doing this. I looked at filters. The function the filter uses would need to get a handle to both lists. One is easy, but I am not sure how it would get a handle to both. I do know the contents of the lists until runtime.

Any help would be appreciated,

Thanks.

like image 812
dublintech Avatar asked Jan 29 '12 15:01

dublintech


People also ask

How do I compare a list of dictionaries?

In the lists of dictionaries you need to compare each dict in your first list to each list in your second dict if there is no structure in the dictionaries. If you have a fixed structure, sort the list of dictionaries according to some key value pair and then start eliminating the different ones.

Can we compare 2 dictionaries in Python?

Using == operator to Compare Two Dictionaries Here we are using the equality comparison operator in Python to compare two dictionaries whether both have the same key value pairs or not.

How do you compare lists in Python?

Python sort() method and == operator to compare lists We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.


1 Answers

Try this:

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]
like image 134
Óscar López Avatar answered Oct 16 '22 06:10

Óscar López