Created
May 1, 2011 22:07
-
-
Save urschrei/950921 to your computer and use it in GitHub Desktop.
Combining dicts, unpacking tuples etc.
This file contains hidden or 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
# produce the cartesian product of input dicts | |
# cartesian product is non-commutative, so order matters | |
import itertools | |
output = list(itertools.product(dict_one, dict_two, dict_three) | |
# now you have a list containing nested tuples of all the input dict combinations: | |
# [(('text_1', value_1), ('text_2', value_2), ('text_3', value_3)), … ] | |
# output list of concatenated text and summed values for each top-level tuple | |
flattened = [[' '.join(text), sum(numbers)] for text, numbers in [zip(*item) for item in output]] | |
# or using a generator expression | |
def gen_list(items) | |
for tuples in items: | |
text, numbers = zip(*tuples) | |
yield ' '.join(text), sum(numbers) | |
print list(gen_list(output)) | |
# you can be even more concise if the same operation is required for keys and values: | |
print map(lambda v: map(' '.join, zip(*v)), output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment