Issue when selecting desired elements from dict_keys in Python

Question:

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?

Asked By: Jiamei

||

Answers:

How about using a regular expression?

import re
rx = re.compile(r'report1b')
items = [report for report in df if rx.search(report)]
Answered By: user17242583

here is a simple but non-robust solution based on the assumption that all your report names follow the format .*report<any int number>:

x = ['A_report10', 'B_report1', 'B_report2', 'B_report10']

report_1s = []

for i in x:
    if i[-7:]=='report1':
        report_1s.append(i)
        print(i)
Answered By: memo