[Python-ideas] dict.items to accept optional iterable with keys to use

Victor Varvariuc victor.varvariuc at gmail.com
Wed Apr 4 10:07:55 CEST 2012

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 all items.

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))))

vic at ubuntu:~/Desktop$ python test.py {1: 'one', 2: 'two', 3: 'three',
4: 'four', 5: 'five'}{1: 'one', 3: 'three', 5: 'five'}

Thanks for the attention.

*Victor Varvariuc*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120404/8d2e3c0a/attachment.html>

More information about the Python-ideas mailing list