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

Python, use a dict over a list please

I have this code and it works. I wrote it to use a list a while back and I am revisiting it and wondering if I can add url and red to a dict rather than a list.

def starts_with_hash(child: str) -> bool:
    if not child.startswith('#'):
        return True


def fetch_blocklist_count(session: requests.Session, url: str, timeout: int)
    try:
        with session.get(url, timeout=timeout) as response:
            filterobj = filter(starts_with_hash, response.text.splitlines())
            red = len(list(filterobj))
            return url, red
    except requests.exceptions.RequestException as e:
        return 'booger'


def test_count(timeout: int=10):
    session = requests.Session()
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = []
        block_host = utils.build_source_list()
        for blocklist in block_host:
            if not blocklist.startswith('#'):
                futures.append(executor.submit(fetch_blocklist_count, session, blocklist, timeout))
        results = [future.result() for future in concurrent.futures.as_completed(futures)]
    return results

>Solution :

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

I will leave my comment here as an answer as well, since you said it solved your problem.

You could change results = [future.result() for future in concurrent.futures.as_completed(futures)] to results = {future.result()[0]: future.result()[1] for future in concurrent.futures.as_completed(futures)}

More details about list comprehension / dictionary comprehension:

https://www.netguru.com/blog/python-list-comprehension-dictionary

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