Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a list based on a second list

Here is what is probably a simple question, but I wasn't able to find a straightforward answer for on my own.

Given two lists, one with only a list of ids, the other with all data, including some ids that we don't care about:
all_data = [['abc', 123], ['cde', 234], ['fgh', 345]]
ids = ['abc', 'fgh']

what is the best way to get the following output, note that it keeps only those that have the same ids: new_data = [['abc', 123], ['fgh', 345]]

My current code does something like:

for x in all_data:
    for y in ids:
         if x[0] == y:
              new_data.append(x)

What woud you do differently? Is there a built-in function that takes care of this that I missed somewhere?

(I say "something like" because it's actually a very long sequence involving sets and all that which is why there is not "pythonic" one-liner to share.)

UPDATE: Well you guys are fun.

How about I make it a little harder. What if instead of "all_data" I have a a dictionary all_data_dict that has several list entries of the same format as "all_data"? Following the rules, I'll make sure to accept the answer to the original question, but if you all want to keep up with the fun, let's see what we get!

like image 476
Lillian Milagros Carrasquillo Avatar asked Dec 01 '25 05:12

Lillian Milagros Carrasquillo


1 Answers

Use a list comprehension where the conditional checks for membership in a set:

>>> all_data = [['abc', 123], ['cde', 234], ['fgh', 345]]
>>> ids = ['abc', 'fgh']
>>> id_set = set(ids)
>>> [s for s in all_data if s[0] in id_set]
[['abc', 123], ['fgh', 345]]
like image 77
Raymond Hettinger Avatar answered Dec 02 '25 19:12

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!