Question

I have this dictionary for grouping filenames and extensions:

email_fields = {'txt': ('subject', 'plaintext_body'),
                'html': ('html_body',)}

I need to get a list of tuples like this:

>>> get_my_list(email_fields)
[('txt', 'subject'), ('txt', 'plaintext_body'), ('html', 'html_body')]

I would like to use something like starmap, product and chain from itertools module to do it:

foo = starmap(product, email_fields.items())
chain.from_iterable(foo)

The problem I have is that product takes two iterables and, as email_fields's keys are strings, I get something like this:

[('t', 'subject'),
 ('t', 'plaintext_body'),
 ('x', 'subject'),
 ('x', 'plaintext_body'),
 ('t', 'subject'),
 ('t', 'plaintext_body')],
 ('h', 'html_body'),
 ('t', 'html_body'),
 ('m', 'html_body'),
 ('l', 'html_body')]

Is there a better way to do it? The closest I got works, but looks uglier:

foo = [product([ext], field) for ext, field in email_fields.items()]
chain.from_iterable(foo)
Was it helpful?

Solution

I would do, manually iterating over the keys and then the values for each key:

[(k, v) for k in email_fields for v in email_fields[k]]

Output:

[('txt', 'subject'), ('txt', 'plaintext_body'), ('html', 'html_body')]

No need for itertools here. :)

OTHER TIPS

You can do it without product itself, by simply iterating the dictionary and then each and every value, like this

print [(k, item) for k in email_fields for item in email_fields[k]]
# [('txt', 'subject'), ('txt', 'plaintext_body'), ('html', 'html_body')]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top