0

I have a question regarding how to filter a dictionary using a loop.

Here is an example of the dictionary:

d = {'beta': ['ABC', '1', '5', '10', '15'],
     'lambda': ['DEF', '3', '30', '22.2', '150'],
     'omega': ['RST','15', '54.4', '150', '75']
}

How do I filter the dictionary to remove keys if the 3rd value in each key is < 100? In other words, after the if function, only omega should be left in the dictionary.
I tried:

for k, v in d.iteritems(): 
    r = float((d[key][2]))
    if r < float(100):
        del d[k]

But it did not work. Any thoughts? New to python programming here.

The new dictionary should just leave the omega key since 150 is greater than 100.

Deuce525
  • 77
  • 1
  • 2
  • 10

1 Answers1

0
def cast_values(v):
    try:
        return float(v)
    except ValueError:
        return v

new_d = {k:[ cast_values(i) for i in v ] for k,v in d.items() if float(v[3]) > 100}

Results:

new_d = {'omega': ['RST', 15, 54.4, 150, 75]}
JClarke
  • 788
  • 1
  • 9
  • 22
  • Jclarke, i think that works but in my actual program where i tried to apply this, it gives me a syntax error of cannot convert string to float. I think its treating the values in the key as strings and not values. Any idea on how to fix that? – Deuce525 Sep 01 '16 at 17:08
  • Unless you're passing the key by mistake instead of the value then you're going to get that error. I tested code with the information you gave and don't get that issue. Make sure you're passing the proper values in `float()` part of the code. – JClarke Sep 01 '16 at 17:12
  • `ValueError: could not convert string to float:` will happen if it is passed something like `float('word')` but will properly cast `float('100')` – JClarke Sep 01 '16 at 17:20
  • so looking again, i'm getting the error cause the values in my dict are shown as '100' , how do i remove the ' ' from the number? i could manually do it in my example, but in my actual program i have thousands of numbers. – Deuce525 Sep 01 '16 at 17:26
  • Is it happening in the new dict that is created ? – JClarke Sep 01 '16 at 17:32
  • my original dictionary has the ' ', i forgot to add that into the example so when i run your syntax, it gives me that cannot convert string to float error – Deuce525 Sep 01 '16 at 17:46
  • I made an update! Next time post your data in the state it was in when you got your error(s) – JClarke Sep 01 '16 at 17:46
  • That works! thank you! I do have one last question, if i do have a string in my key, not just values to convert, is there a way to keep the string a string? See updated question above. Thanks! – Deuce525 Sep 01 '16 at 19:04
  • It worked! after a few modifications to another part of my code! – Deuce525 Sep 02 '16 at 02:02