Skip to content

Instantly share code, notes, and snippets.

@zackmdavis
Created May 16, 2017 23:19
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 zackmdavis/c64080f93ac80c4755b6cf653e97ce04 to your computer and use it in GitHub Desktop.
Save zackmdavis/c64080f93ac80c4755b6cf653e97ce04 to your computer and use it in GitHub Desktop.
# Alison asks—
#
# once i have a dictionary mapping one thing to a list of things
# how do i generate tuples of the one thing to each of the things in the list
# of the things it is mapped to
# e.g. { a : [ (1, 2), (2, 4) ], b : [ (3, 5), (7, 9) ] }
# to [(a, 1, 2), (a, 2, 4), (b, 3, 5), (b, 7, 9)]
# My reply—
m = {'a': [(1, 2), (2, 4)], 'b': [(3, 5), (7, 9)]}
expected = [('a', 1, 2), ('a', 2, 4), ('b', 3, 5), ('b', 7, 9)]
result = []
for key, val in m.items():
for subval in val:
result.append((key,) + subval)
assert set(result) == set(expected)
# but if this is for a CSV, Python has a module for that which might be helpful
import csv
# albeit at the cost of some upfront investment to RTFM
# (https://docs.python.org/3/library/csv.html)
@schnaigs
Copy link

schnaigs commented May 16, 2017

thanks! got it in a comprehension
[(key, ) + subval for (key, val) in m.items() for subval in val]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment