for/ if against dict - one liner

Thomas Jollans tjol at tjol.eu
Tue Nov 14 05:03:07 EST 2017


On 2017-11-14 07:29, Stefan Ram wrote:
> Andrew Z <formisc at gmail.com> writes:
>> i wonder how do i get the "for" and "if" to work against a dictionary in
>> one line?
> 
> dict ={ 1 : "one", 2 : "two", 3 : "three" }
> print( *( ( str( key )+ ' ' + str( dict[ key ])) for key in dict if key >= 2 ), sep='\n' )
> 
>   prints:
> 
> 2 two
> 3 three
> 

We can build something nicer than that, surely. The repeated str() calls
and dictionary lookups just look like noise to my eyes.

print('\n'.join(f'{k} {v}' for k, v in dict.items() if k >= 2))

But indeed, you can build concise dictionary filters like that with
generator expressions and list comprehensions.


-- 
Thomas Jollans



More information about the Python-list mailing list