Python syntax: mutating/reducing a defaultdict?

171 Views Asked by At

I wasn't sure what the term is, but basically I have a word_set in the form of a defaultdict [(word, value), ...] that came from a function that parsed some raw data.

I have other functions: reduceVal(word_set, min_val), reduceWord(word_set, *args), etc that removes pairs that: have a value less than min_val, have their (word) in [args], respectively. They all pretty much follow the same structure, e.g.

def reduceVal(word_set, value):
    "Returns word_set with (k, v) pairs where v > value)"
    rtn_set = defaultdict()
    for (k, v) in word_set.items():
        if v > value:
            rtn_set.update({k:v})
    return rtn_set

I was wondering if there was a more concise, or pythonic, way of expressing this, without building a new rtn_set or maybe even defining an entire function

2

There are 2 best solutions below

0
Ashwini Chaudhary On

Use a dict-comprehension, defaultdict is not required here:

new_dict = {k:v for k, v in word_set.items() if v > value}

on py2.x you should use word_set.iteritems() as it returns an iterator.

0
John Kugelman On

If you learn to use dict comprehensions you don't need to have separate functions for all of these different filters. For instance, reduceVal and reduceWord could be replaced with:

# Python 2.7+
{w: v for w, v in word_set.items() if v > value}
{w: v for w, v in word_set.items() if w in args}

# Python 2.6 and earlier
dict((w, v) for w, v in word_set.iteritems() if v > value)
dict((w, v) for w, v in word_set.iteritems() if w in args)