Function to prune dictionary keys not working

G

Girish Sahani

hi ppl,
Here is a simple function to remove those keys of a dictionary whose
values are less than some specified value. But it isnt working. Please
help.

def prune(d,cp):
l = []
for rule,value in d.iteritems():
#print value
if value >= cp:
l.append(rule)
return l

'0.50', 'c=>ba': '0.33', 'bd=>a': '1.00', 'a=>cb': '0.33', 'ea=>c':
'0.67', 'a=>cd': '0.50', 'e=>ac': '0.40', 'e=>ab': '0.20', 'c=>bd':
'0.33', 'e=>cb': '0.40', 'ed=>b': '0.25', 'ed=>c': '0.50'} print "code not working :(("

code not working :((
 
J

John Machin

hi ppl,
Here is a simple function to remove those keys of a dictionary whose
values are less than some specified value. But it isnt working. Please
help.

def prune(d,cp):
l = []
for rule,value in d.iteritems():
#print value
if value >= cp:
l.append(rule)
return l

'0.50', 'c=>ba': '0.33', 'bd=>a': '1.00', 'a=>cb': '0.33', 'ea=>c':
'0.67', 'a=>cd': '0.50', 'e=>ac': '0.40', 'e=>ab': '0.20', 'c=>bd':
'0.33', 'e=>cb': '0.40', 'ed=>b': '0.25', 'ed=>c': '0.50'} print "code not working :(("

code not working :((

|>> '1.00' >= 0.5
True
|>> '0.33' >= 0.5
True

Python (correctly) does very little (guesswork-based) implicit type
conversion.

It looks like the values in your dictionary should stored as floats, not
as strings.

HTH,
John
 
S

Serge Orlov

|>> '1.00' >= 0.5
True
|>> '0.33' >= 0.5
True

Python (correctly) does very little (guesswork-based) implicit type
conversion.

At the same time, Python (incorrectly :) compares incomparable objects.
 
B

Bruno Desthuilliers

Girish Sahani a écrit :
hi ppl,
Here is a simple function to remove those keys of a dictionary whose
values are less than some specified value.
>
But it isnt working.

"is not working" is the worst possible description of a problem.
def prune(d,cp):
l = []
for rule,value in d.iteritems():
#print value
if value >= cp:
l.append(rule)
return l

This doesn't remove anything from the dict - it returns a list of keys
for which values are >= cp value. FWIW, a simple expression is enough to
do this:
[k for k, v in d.items() if v >= cp]

The algorithm for what you described would be:
def prune(dic, cmp):
for k, v in dic.items():
if v < cmp:
del dic[k]

'0.50', 'c=>ba': '0.33', 'bd=>a': '1.00', 'a=>cb': '0.33', 'ea=>c':
'0.67', 'a=>cd': '0.50', 'e=>ac': '0.40', 'e=>ab': '0.20', 'c=>bd':
'0.33', 'e=>cb': '0.40', 'ed=>b': '0.25', 'ed=>c': '0.50'}

You are comparing floats with strings...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top