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