Saturday, March 31, 2012

Want a new feature for dicts in Python

Want it badly, but how?
class NewDict(dict):

    def items(self, keys=()):
        """Another version of dict.items() which accepts specific keys to use."""
        for key in keys or self.keys():
            yield key, self[key]
        
       
a = NewDict({
    1: 'one',
    2: 'two',
    3: 'three',
    4: 'four',
    5: 'five'
})

print(dict(a.items()))
print(dict(a.items((1, 3, 5))))
Sometimes you want a dict which is subset of another dict. It would nice if dict.items accepted an optional list of keys to return. If no keys are given - use default behavior - get items for all dict keys.
vic@ubuntu:~/Desktop$ python test.py 
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
{1: 'one', 3: 'three', 5: 'five'}

No comments:

Post a Comment