Python - Merging 2 lists of tuples by checking their values
Question: I have lists like this:

    
    
    a = [('JoN', 12668, 0.0036), ('JeSsIcA', 1268, 0.0536), ('JoN', 1668, 0.00305), ('King', 16810, 0.005)]
    b = [('JoN', 12668, 0.0036), ('JON', 16680, 0.00305), ('MeSSi', 115, 0.369)]
    

I want the resultant list to be like:

    
    
    result = [(('JoN', 12668, 0.0036), ('JoN', 12668, 0.0036)), (('JoN', 1668, 0.00305), ('JON', 16680, 0.00305)), (('King', 16810, 0.005), None), (None, ('MeSSi', 115, 0.369))]
    

I have tried nested loops, sets, map, zip but failed to achieve this output.
kindly help me out.


Answer: Convert `a` and `b` to dictionaries first using the first(use `str.lower()` in
it) and third item as key and then later on loop on the union of the keys in a
list comprehension to get the desired output:

    
    
    >>> from pprint import pprint
    >>> dct_a = {(x[0].lower(), x[2]): x for x in a}
    >>> dct_b = {(x[0].lower(), x[2]): x for x in b}
    >>> out = [(dct_a.get(k), dct_b.get(k)) for k in set(dct_a).union(dct_b)]
    >>> pprint(out)
    [(('JoN', 12668, 0.0036), ('JoN', 12668, 0.0036)),
     (('JoN', 1668, 0.00305), ('JON', 16680, 0.00305)),
     (('King', 16810, 0.005), None),
     (('JeSsIcA', 1268, 0.0536), None),
     (None, ('MeSSi', 115, 0.369))]
    

