Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check list for part of value and return whole value

I have a master list of ID numbers and another list of partial ID numbers. I need to check if the partial ID number is in the master list. If so, I need to return the whole ID number into a new list. What I have:

master_list = ['20000-K-A', '20000-K-B', '20000-K-C', '30000-R-X', '30000-R-V', '30000-R-F']

partial_list = [20000, 40000, 500000]

new_list =[]

for x in partial_list:
  if x in master_list:
    new_list.append(x)

print(new_list)

Now this only works if the partial ID number is EXACTLY what is in the master list. How do I return the value from the master list so that I can add it to the new list?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option is to create a lookup dictionary first from master_list (note that the master_list is a list of strings while partial_list is a list of integers, so we need to cast the prefix to int):

d = {}
for item in master_list:
    k, _ = item.split('-', maxsplit=1)
    d.setdefault(int(k), []).append(item)

which looks like:

{20000: ['20000-K-A', '20000-K-B', '20000-K-C'], 
 30000: ['30000-R-X', '30000-R-V', '30000-R-F']}

Then iterate over partial_list to get the partially matching Ids:

new_list =[]
for x in partial_list:
    new_list.extend(d.get(x, []))

Output:

['20000-K-A', '20000-K-B', '20000-K-C']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading