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

How to select desired elements from dict_keys in Python

I have a list of disctionary keys ['A_report1', 'A_report2', ..., 'A_report10','B_report1', 'B_report2', ..., 'B_report10',]. I want to extract all ‘report1’ from this dict_keys. In other words, I should only get 'A_report1' and 'B_report1'.

Here’s the code I tried:

[report for report in list(df.keys()) if 'report1' in report]

Issue: It’ll return 'A_report10' and 'B_report10' as well, I only want report1’s. Anyway to fix this?

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 :

How about using a regular expression?

import re
rx = re.compile(r'report1\b')
items = [report for report in list(df.keys()) if rx.search(report)]
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