On 2017-11-14 07:29, Stefan Ram wrote:
> Andrew Z <[email protected]> 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
--
https://mail.python.org/mailman/listinfo/python-list