Skip to content Skip to sidebar Skip to footer

Use Two Keys To Create A List Of Dictionaries In A Not In B

This is a more complex edit on a previous question. Previously I asked about using only one key, now I would like to learn about how to use two keys: Suppose there is list of dicti

Solution 1:

Thanks to the comments for encouraging me to solve this on my own.

For those lost beginners trying to find documentation on :

[x for x in y if condition]

It's called a comprehension. I just started using python and had no idea this thing had a proper name. It's also difficult to google because it is made of symbols and prepositions. Now you know and can look up all the documentation on comprehensions!

Here is the solution, it was super simple once I looked up how comprehensions can handle two elements instead of one

list_a = [
    {'x' : 1,  'y': 10, 'z': 100},
    {'x' : 1,  'y': 11, 'z': 100},
    {'x' : 1,  'y': 12, 'z': 100},
    {'x' : 2,  'y': 10, 'z': 200},
    {'x' : 2,  'y': 11, 'z': 200},
    {'x' : 2,  'y': 12, 'z': 200}
]

list_b = [
    {'x' : 1,  'y': 10, 'fruit': 'orange'},
    {'x' : 1,  'y': 12, 'fruit': 'apple'},
    {'x' : 2,  'y': 12, 'fruit': 'banana'}
]

list_c = [

    {'x' : 1,  'y': 11, 'z': 100},
    {'x' : 2,  'y': 10, 'z': 200},
    {'x' : 2,  'y': 11, 'z': 200}
]



list_b_set = {(b['x'], b['y']) for b in list_b}
list_c_new = [a for a in list_a if (a['x'],a['y']) not in list_b_set]

list_c_new == list_c

Post a Comment for "Use Two Keys To Create A List Of Dictionaries In A Not In B"