Skip to content

Instantly share code, notes, and snippets.

@zagorulkinde
Created April 24, 2015 14:07
Show Gist options
  • Save zagorulkinde/41087247d6b800fbbc57 to your computer and use it in GitHub Desktop.
Save zagorulkinde/41087247d6b800fbbc57 to your computer and use it in GitHub Desktop.
Python lazy zip gen
def zip_gen(list_key, list_value):
'''
>>> dict([(a,b) for (a,b) in zip_gen([1,2,3,4], ['a','b','c','d'])])
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> dict([(a,b) for (a,b) in zip_gen([1,2], ['a','b','c','d'])])
{1: 'a', 2: 'b'}
>>> dict([(a,b) for (a,b) in zip_gen([1,2,3,4], ['a'])])
{1: 'a', 2: None, 3: None, 4: None}
'''
iter_key = list_key.__iter__()
iter_value = list_value.__iter__()
while True:
try:
key = iter_key.next()
try:
value = iter_value.next()
yield(key, value)
except StopIteration as vse:
yield (key, None)
except StopIteration as kse:
return
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment