user6037143 - 5 months ago 23

Python Question

`start = 0`

limit = 100

count = 10

total_count = 1000

pages = {}

for i in range(1, count+1):

pages[i] = start

start += limit

print pages

{1: 0, 2: 100, 3: 200, 4: 300, 5: 400, 6: 500, 7: 600, 8: 700, 9: 800, 10: 900}

How can I achieve the same result using dictionary comprehension? I can't seem to be able to increment the value of variable 'start' after each iteration with dict comprehension.

Is it possible to achieve the same result comprehension?

Answer

Use mathematics:

```
pages = {(i+1): 100 * i for i in range(count)}
```

Since `start`

starts at zero and keeps adding `100`

, we can use multiplication to find where it should be at each point. If `start`

and `limit`

aren't always going to be what they are here, you can still do this:

```
pages = {(i+1): start + (limit * i) for i in range(count)}
```