Amit Panthi
Amit Panthi

Reputation: 9

How to write below code in any other way?

How can I rewrite the following comprehesion?

positive_crawls = [{'url': page['url'], 'hour': hour-1, 'updated': True} 
                   for page in crawl_json 
                   for hour in page['positive checks']]

Upvotes: 0

Views: 41

Answers (2)

stacksonstacks
stacksonstacks

Reputation: 9313

As others have said, without a goal for the rewrite in mind there's lot's of room for interpretation.

Here's one

from dataclasses import dataclass

@dataclass
class Crawl:
    url: str
    hour: int
    updated: bool = True

def get_crawls(crawl_json):
    for page in crawl_json:
        for hour in page['positive checks']:
            yield Crawl(page['url'], hour - 1).asdict()

positive_crawls = list(get_crawls(crawl_json))

Upvotes: 0

lmiguelvargasf
lmiguelvargasf

Reputation: 69755

If you mean how to rewrite that comprehension using loops instead, this is the way:

positive_crawls = []

for page in crawl_json:
    for hour in page['positive checks']:
        positive_crawls.append({'url': page['url'], 'hour': hour-1, 'updated': True})

However, keep in mind that it is very likely that your comprehension is faster than using this two for-loops.

Upvotes: 1

Related Questions