For specific keys , extract non empty values in a dictionary

Ganesh Pal ganesh1pal at gmail.com
Sun Jun 17 10:47:30 EDT 2018


>  >>> {k: o_num[k] for k in wanted & o_num.keys() if o_num[k] is not None}

Thanks peter this looks better ,  except  that I will need to use the
logial 'and' operator or else I will get a  TypeError

>>> {k: o_num[k] for k in wanted & o_num.keys() if o_num[k] is not None}

TypeError: unsupported operand type(s) for &: 'set' and 'list'


Example :

>>>print {k: o_num[k] for k in wanted and o_num.keys() if o_num[k] is not
None}
   {'nine': 9, 'five': 5, 'three': 3, 'one': 1}



On Sat, Jun 16, 2018 at 11:12 PM, Peter Otten <__peter__ at web.de> wrote:

> 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.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list