I have a dict that has many elements, I want to write a function that can return the elements in the given index range(treat dict as array):
get_range(dict, begin, end):
return {a new dict for all the indexes between begin and end}
How that can be done?
EDIT: I am not asking using key filter… eg)
{"a":"b", "c":"d", "e":"f"}
get_range(dict, 0, 1) returns {"a":"b", "c":"d"} (the first 2 elements)
I don’t care the sorting…
Actually I am implementing the server side paging…
Edit: A dictionary is not ordered. It is impossible to make
get_rangereturn the same slice whenever you have modified the dictionary. If you need deterministic result, replace yourdictwith acollections.OrderedDict.Anyway, you could get a slice using
itertools.islice:The previous answer that filters by key is kept below:
With @Douglas‘ algorithm, we could simplify it by using a generator expression:
BTW, don’t use
dictas the variable name, as you can see heredictis a constructor of dictionary.If you are using Python 3.x, you could use dictionary comprehension directly.