On 2018-06-17 15:47, Ganesh Pal wrote:
>>> {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'
Peter said that you need to use viewkeys() instead of keys() in Python 2:
>>> {k: o_num[k] for k in wanted & o_num.viewkeys() if o_num[k] is not
None}
Using 'and' instead won't give the correct result.
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 <__pete...@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