python: how to get a subset of dict -
i have dict has many elements, want write function can return elements in given index range(treat dict array):
get_range(dict, begin, end): return {a new dict indexes between begin , end}
how can done?
edit: 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 sorting... implementing server side paging...
edit: dictionary not ordered. impossible make get_range
return same slice whenever have modified dictionary. if need deterministic result, replace dict
with collections.ordereddict
.
anyway, slice using itertools.islice
:
import itertools def get_range(dictionary, begin, end): return dict(itertools.islice(dictionary.iteritems(), begin, end+1))
the previous answer filters key kept below:
with @douglas' algorithm, simplify using generator expression:
def get_range(dictionary, begin, end): return dict((k, v) k, v in dictionary.iteritems() if begin <= k <= end)
btw, don't use dict
variable name, can see here dict
constructor of dictionary.
if using python 3.x, use dictionary comprehension directly.
def get_range(dictionary, begin, end): return {k: v k, v in dictionary.items() if begin <= k <= end}
Comments
Post a Comment