For specific keys , extract non empty values in a dictionary

Peter Otten __peter__ at web.de
Sun Jun 17 17:42:31 EDT 2018


Dennis Lee Bieber wrote:

> On Sun, 17 Jun 2018 17:37:25 +0100, MRAB <python at mrabarnett.plus.com>
> declaimed the following:
> 
>>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}
>>
> 
> What's wrong with the simple
> 
>>>> 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" ]
>>>> 
>>>> { k : o_num[k] for k in args_list if o_num.get(k, None) is not None }
> {'nine': 9, 'three': 3, 'one': 1}
>>>> 

It's hidden here because of the removal of None values, but in the generic 
case when you say

"give me all x in a that are also in b"

instead of

"give me the intersection of a and b"

you are overspecifying the problem.




More information about the Python-list mailing list