'Issue when selecting 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(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 1:[1]
How about using a regular expression?
import re
rx = re.compile(r'report1\b')
items = [report for report in df if rx.search(report)]
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | juanpa.arrivillaga |
Solution 2 |