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

Generate a binary values dictionary by searching in two lists

I have two lists

list1=['ABC','DBA','CBA','RBA','DCA','RMA']
list2=['ABC,'DBA','RMA']

Expected Output

{'ABC':1,'DBA':1,'CBA':0,'RBA':0,'DCA':0,'RMA':1}

if the values of list1 are present in list2 then the values of output dictionary would be 1, otherwise 0.

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 :

If the size of list2 is small, you can use a simple dictionary comprehension:

{key: int(key in list2) for key in list1}

However, if list2 is long, you should turn it into a set for faster lookups:

lookup_set = set(list2)
{key: int(key in lookup_set) for key in list1}

Both of these output:

{'ABC': 1, 'DBA': 1, 'CBA': 0, 'RBA': 0, 'DCA': 0, 'RMA': 1}
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