Anyway to clarify this code? (dictionaries)
Bengt Richter
bokr at oz.net
Wed Nov 23 05:59:10 EST 2005
On 22 Nov 2005 19:52:40 -0800, "bonono at gmail.com" <bonono at gmail.com> wrote:
>
>Bengt Richter wrote:
>> >>> def my_search(another, keys, x): return dict((k,another[k]) for k in keys if another[k]>x)
>> ...
>> >>> my_search(another, 'cb', .3)
>> {'b': 0.35806602909756235}
>> >>> my_search(another, 'abcd', .4)
>> {'a': 0.60649466203365532, 'd': 0.77440643221840166}
>>
>Do you need to guard the case "k not in another" ?
>
Good catch ;-)
What did the OP want as a value if any for that case? None? or no entry at all?
Taking a cue from Mike, I like the set method of getting the common keys, to eliminate the entry (untested)
def my_search(another, keys, x):
return dict((k,another[k]) for k in (set(another)&set(keys)) if another[k]>x)
otherwise, to get Nones, maybe (untested)
def my_search(another, keys, x):
return dict((k,another.get(k)) for k in keys if k not in another or another[k]>x)
Regards,
Bengt Richter
More information about the Python-list
mailing list