List comp help

rurpy at yahoo.com rurpy at yahoo.com
Sun Jul 14 20:32:34 CEST 2013


On 07/14/2013 11:16 AM, Chris Angelico wrote:
> On Mon, Jul 15, 2013 at 3:10 AM, Joseph L. Casale
> <jcasale at activenetwerx.com> 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]
>>
>> 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?
> 
> Yeah, it's remarkably easy too! Try this:
> 
> [(k, x) for k, v in my_dict.items() for x in v or [None]]
> 
> An empty list counts as false, so the 'or' will then take the second
> option, and iterate over the one-item list with None in it.

Or more simply:

  [(k, v or None) for k, v in my_dict.items()]

This assumes that all the values in my_dict are lists, and not
other false values like 0, which would also be replaced by None. 



More information about the Python-list mailing list