Search code examples
pythonpandasfor-loopif-statementextract

Issue when selecting desired elements from dict_keys in Python


I have a list of dictionary 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(dictionary.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?


Solution

  • How about using a regular expression?

    import re
    rx = re.compile(r'report1\b')
    items = [report for report in df if rx.search(report)]