For specific keys , extract non empty values in a dictionary

Peter Otten __peter__ at web.de
Sat Jun 16 13:42:34 EDT 2018


Ganesh Pal wrote:

> *How do I check  few specific/selected  keys in a dictionary and extract
> their values if they are not empty*

You mean not None.

> o_num  = {'one': 1,
>           'three': 3,
>           'bar': None,
>           'five' : 5,
>           'rum' : None,
>           'seven' : None,
>           'brandy': None,
>           'nine' : 9,
>           'gin': None}

> args_list = ["one","three","seven","nine"]

> *Output:*
> 
> *1 3 9*

>>> wanted = {"one", "three", "seven", "nine"}
>>> {k: o_num[k] for k in wanted & o_num.keys() if o_num[k] is not None}
{'one': 1, 'nine': 9, 'three': 3}

> I am a Python 2.7 user and on Linux box

You have to replace keys() with viewkeys() in Python 2.




More information about the Python-list mailing list