Python syntax: mutating/reducing a defaultdict? -
i wasn't sure term is, have word_set
in form of defaultdict [(word, value), ...]
came function parsed raw data.
i have other functions: reduceval(word_set, min_val)
, reduceword(word_set, *args)
, etc removes pairs that: have value less min_val, have (word) in [args], respectively. pretty follow same structure, e.g.
def reduceval(word_set, value): "returns word_set (k, v) pairs v > value)" rtn_set = defaultdict() (k, v) in word_set.items(): if v > value: rtn_set.update({k:v}) return rtn_set
i wondering if there more concise, or pythonic, way of expressing this, without building new rtn_set or maybe defining entire function
if learn use dict comprehensions don't need have separate functions of these different filters. instance, reduceval
, reduceword
replaced with:
# python 2.7+ {w: v w, v in word_set.items() if v > value} {w: v w, v in word_set.items() if w in args} # python 2.6 , earlier dict((w, v) w, v in word_set.iteritems() if v > value) dict((w, v) w, v in word_set.iteritems() if w in args)
Comments
Post a Comment