Search code examples
pythonpython-3.xzippython-itertoolschain

How to create a dictionary with itertools by combining a tuple and static string


Currently I have an iterator that produces:

(0, 10), (10, 20), (20, 30), (30, 40), (40, 50), (50, 56), (56, None)

What I'm looking to produce:

[["current": "0", "next":"10", "default": "value"], ["current": "10", "next":"20", "default": "value"]], 

What I have so far:

('default', (0, 10)), ('default', (10, 20)), ('default', (20, 30)), ('default', (30, 40)), ('default', (40, 50)), ('default', (50, 56)), ('default', (56, None))

What changes can I make to produce dictionaries from my list of tuples?

Here is the code to reproduce what I have:

start = 0
end = 56
step = 10

part = itertools.islice(range(end), start, end, step)
end = [end]
iterables = itertools.chain(part, end)

items, nexts = itertools.tee(iterables)
# items = [0, 10, 20, 30, 40, 50, 56]
nexts = itertools.chain(itertools.islice(nexts, 1, None), [None])
# next = [10, 20, 30, 40, 50, 56, None]
results = itertools.zip_longest(items, nexts)
# [(0, 10), (10, 20), (20, 30), (30, 40), (40, 50), (50, 56), (56, None)]

static = "default"

result = zip(itertools.repeat(static),results)
print(list(result))

Note, I would love to only use itertools to complete this if possible, I really don't want to hold an entire list of dictionaries in memory.


Solution

  • Writing your own generator function could be more readable in such cases. For example:

    def items():
        start = 0
        end = 56
        step = 10
    
        while True:
            d = {"current": start,
                 "next": start + step if start + step < end else end if start < end else None,
                 "default": "value"}
            yield d
            if start >= end:
                break
            else:
                start += step
                if start > end:
                    start = end
    
    print(list(items()))
    

    output:

    [{'current': 0, 'next': 10, 'default': 'value'}, 
     {'current': 10, 'next': 20, 'default': 'value'}, 
     {'current': 20, 'next': 30, 'default': 'value'}, 
     {'current': 30, 'next': 40, 'default': 'value'}, 
     {'current': 40, 'next': 50, 'default': 'value'}, 
     {'current': 50,'next': 56, 'default': 'value'}, 
     {'current': 56, 'next': None, 'default': 'value'}]