1

I'm experimenting with using dictionaries in Python as an alternative to switch cases. I'd like to use a range of values as a key in my dictionary. I have something similar to the code below:

dispatcher = {
    0 < col_value <= .5: "avg",
    .5 < col_value <= .9: "value",
}

for col in self.missing_ratios_dict:

    self.to_do_list[col] = dispatcher.get(self.missing_ratios_dict[col], "drop")

missing_ratios_dict is a dictionary populated with pairs like "Age" : .199, "Name": 0.0, and so on.

What I would like for this to do is if the value of the column is between 0 and .5 to add "avg" to my to_do_list, if it's between .5 and .9 to add "value" to my to_do_list, and otherwise to add "drop" to my to_do_list.

Currently what it's actually doing is adding "value" if the value is 0.0 and "drop" otherwise.

1 Answers1

2

dict can not have hashable range as key. However, you may create a key denoting the range in the form of tuple, but it is of no use as you can not directly call dict.get(x) to get the value from key with tuple as (y1, y2) (where y1 < x keys to check if value is part of any range.

I will suggest you to create a function like this for finding the category:

def get_type(value):
    category = None
    if 0 < value < 0.5:
         category =  "avg"
    elif 0.5 <= value < 0.8:
         category = "good"
    return category
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126