Home > Software engineering >  How i can remove key/value from a list of tuples by key from another list of tuples?
How i can remove key/value from a list of tuples by key from another list of tuples?

Time:10-12

I need to remove keys and values in a list of tuples by keys from another list of tuples

list_tuple = [('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393), ('DRR', 287.987), ('SSW', 487.294), ('EOF', 546.972), ('LHM', 687.54)]

list_tuple_keys = [('DRR', 'Error time'), ('EOF', 'Error time'), ('LHM', 'Error time'), ('SSW', 'Error time')]

example = [('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393)]

CodePudding user response:

One way is to make a hashmap for filtering target list.

filter_keys = {t[0]: True for t in list_tuple_keys}
result = [t for t in list_tuple if not filter_keys.get(t[0], False)]

CodePudding user response:

Given the code

given = [('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393), ('DRR', 287.987), ('SSW', 487.294), ('EOF', 546.972), ('LHM', 687.54)]
to_remove = [('DRR', 'Error time'), ('EOF', 'Error time'), ('LHM', 'Error time'), ('SSW', 'Error time')]
expected = [('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393)

I'd first reduce the list of items to remove to just the minimum information needed:

keys = []
for item in to_remove:
    keys.append(item[0])

or keys = [t[0] for t in to_remove] as a list comprehension.

Then you can go through the list of items to be filtered and skip the unwanted ones:

result = []
for item in given:
    if not item[0] in keys:
        result.append(item)

or result = [t for t in given if not t[0] in keys] as a list comprehension.

Finally

print(result)

results in

[('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393)]

CodePudding user response:

You can do this with list comprehension

result = [item for item in list_tuple if item[0] not in dict(list_tuple_keys)]

# result
[('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393)]

Converted list_tuple_keys into a dictionary, so it's easy to check the membership.

  • Related