Created
May 16, 2017 23:19
-
-
Save zackmdavis/c64080f93ac80c4755b6cf653e97ce04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks! got it in a comprehension
[(key, ) + subval for (key, val) in m.items() for subval in val]