How To Use A Range For Dict Keys?
Solution 1:
range()
in Python 2 is merely a function that returns a list of integers, it is not itself a type of object. And you wouldn't want to use lists here, no, because they contain all integers in the range.
You could use xrange()
objects instead, these are hashable, and only store the start and end values. However, unless you plan to use otherxrange()
objects to test these keys, a dictionary with such keys is not very useful, you'd have to loop over the dictionary to test your rate against each xrange
object manually.
Your success rate dictionary could more simply be replaced by maths; just round your numbers up to the nearest multiple of 10 (simply using floor division):
success_rate = ((amount_of_urls // 10) + 1) * 10
Do test if that resulting value is between 10 and 100:
10 <= success_rate <= 100
Solution 2:
RangeKeyDict class could be able to handle cases like this, which is more general and easy to use. For usage, check the codes in __main__
to install it using:
pip install range-key-dict
Usage:
from range_key_dict import RangeKeyDict
if __name__ == '__main__':
range_key_dict = RangeKeyDict({
(0, 100): 'A',
(100, 200): 'B',
(200, 300): 'C',
})
# test normal caseassert range_key_dict[70] == 'A'assert range_key_dict[170] == 'B'assert range_key_dict[270] == 'C'# test case when the number is floatassert range_key_dict[70.5] == 'A'# test case not in the range, with default valueassert range_key_dict.get(1000, 'D') == 'D'
https://github.com/albertmenglongli/range-key-dict
Reference: Please check the answer in this post: Range as dictionary key in Python
Post a Comment for "How To Use A Range For Dict Keys?"