List comp help

Terry Reedy tjreedy at udel.edu
Mon Jul 15 06:46:05 CEST 2013


On 7/14/2013 1:10 PM, Joseph L. Casale wrote:
> I have a dict of lists. I need to create a list of 2 tuples, where each tuple is a key from
> the dict with one of the keys list items.
>
> my_dict = {
>      'key_a': ['val_a', 'val_b'],
>      'key_b': ['val_c'],
>      'key_c': []
> }
> [(k, x) for k, v in my_dict.items() for x in v]

The order of the tuples in not deterministic unless you sort, so if 
everything is hashable, a set may be better.

> This works, but I need to test for an empty v like the last key, and create one tuple ('key_c', None).
> Anyone know the trick to reorganize this to accept the test for an empty v and add the else?

When posting code, it is a good idea to includes the expected or desired 
answer in code as well as text.

pairs = {(k, x) for k, v in my_dict.items() for x in v or [None]}
assert pairs == {('key_a', 'val_a'), ('key_a', 'val_b'),
    ('key_b', 'val_c'), ('key_c', None)}


-- 
Terry Jan Reedy




More information about the Python-list mailing list