Python, use a dict over a list please

Question:

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
Asked By: UneRoue

||

Answers:

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

Answered By: Damian Robert
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.