Anyway to clarify this code? (dictionaries)

Bengt Richter bokr at oz.net
Tue Nov 22 22:51:37 EST 2005


On 22 Nov 2005 17:58:28 -0800, "javuchi" <javuchi at gmail.com> wrote:

>I've been searching thru the library documentation, and this is the
>best code I can produce for this alogorithm:
>
>I'd like to return a dictionary which is a copy of 'another' dictionary
>whoes values are bigger than 'x' and has the keys 'keys':
>
>def my_search (another, keys, x):
>        temp = another.fromkeys(keys)
>        return dict([[k,v] for k in temp.keys() for v in temp.values()
>if v>=x])
>
>Is there any way to improve this code?
>I want to avoid converting the dictionary to a list and then to a
>dictionay. Are there speed penalties for such a conversion?
>
>Bye.
>
 >>> another = dict(zip('abcd', iter(random.random, 2)))
 >>> import random
 >>> another = dict(zip('abcd', iter(random.random, 2)))
 >>> for k,v in another.items(): print k,v
 ...
 a 0.606494662034
 c 0.273998760342
 b 0.358066029098
 d 0.774406432218

If keys are few compared to the number of keys in another, this may be prefereable:

 >>> 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}

This sounds like homework though ... ?

Regards,
Bengt Richter



More information about the Python-list mailing list