Skip to content

Instantly share code, notes, and snippets.

@mattwigway
Created July 13, 2018 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattwigway/26bf5bf0fdb7a7f55da0f2b4fcd0e587 to your computer and use it in GitHub Desktop.
Save mattwigway/26bf5bf0fdb7a7f55da0f2b4fcd0e587 to your computer and use it in GitHub Desktop.
# similar to Python's built in zip function, but yielding named tuples instead of tuples.
# i.e. list(namedzip(a=[1, 2], b=[3, 4])) => [namedzipitem(a=1, b=3), namedzipitem(a=2, b=4)]
# Author: Matthew Wigginton Conway <mwconway@asu.edu>
# feel free to use and share
from collections import namedtuple
def namedzip (**kwargs):
keys = list(kwargs.keys())
typ = namedtuple('namedzipitem', keys)
length = len(kwargs[keys[0]])
if not all([len(kwargs[key]) == length for key in keys[1:]]):
raise IndexError('lengths much match')
for i in range(length):
yield typ(**{ key: kwargs[key][i] for key in keys })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment