Reputation: 566
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?
Upvotes: 0
Views: 855
Reputation: 385
I ran into this question when I was looking for a solution to increment a variable which I want to be a part of each key in the dictionary. The solutions here didn't assist in my case so I used Python's enumerate() method for that. Here's what my solution would look like for the question posted here:
start = 0
limit = 100
count = 10
pages2 = {(j + 1): start + i * limit for i, j in enumerate(range(count))}
print(pages2)
Upvotes: 0
Reputation: 20336
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)}
Upvotes: 2
Reputation: 18446
start = 0
limit = 100
count = 10
pages2 = {(i + 1): start + i * limit for i in range(count)}
print pages2
Upvotes: 1