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!
being that many have used dicts or LC I thought I should show
filteras for the second part.