Mark W
Mark W

Reputation: 37

Generate tuples of intervals from dict in Python

Is there a list comprehension way of doing the following?

The output should be: [(0, 5, 'a'), (5, 15, 'b'), (15, 23, 'c')]

a = { 'a' : 5, 'b' : 10, 'c' : 8 }

items = []

i = 0

for k, v in a.iteritems():
    items.append((i, i+v, k))
    i += v

print items

Upvotes: 1

Views: 302

Answers (1)

Eugene Soldatov
Eugene Soldatov

Reputation: 10145

Sometime one-liners aren't so good:

items = [(sum(map(a.get, sorted(a)[:i])), sum(map(a.get, sorted(a)[:i+1])), key) for i, key in enumerate(sorted(a))]

Variant with loop seems much more readable:

items = []
i = 0
for key in sorted(a):
    items.append((i, i+a[key], key))
    i += a[key]

Anyway you should sort dictionary's keys, because dictionary is unordered in Python.

Upvotes: 2

Related Questions