Exie Exie - 1 month ago 17
Python Question

Subset fields from an ordereddict?

So, I have an ordered dictionary, and its has a pile of key/value pairs. I can extract ALL them with the items() method. But what if I only want to select SOME of them ?

>>> import collections
>>> d = collections.OrderedDict({'banana': 3, 'apple': 4, 'pear': 1,'orange': 2})
>>> d.items()
[('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]


What if I just want apple and banana ?

Is there a way I can specify the keys I want ?

>>> d['apple','banana'] <-- does not work


I was considering using a list comprehension at the end to filter the results, but seems messy and I hope there is a better way.

Answer

You'll most likely wind up using a list comprehension one way or another. Here is a way to bury the list comprehension in a method implementation:

from collections import OrderedDict

class MultOrderedDict(OrderedDict):
    def __getitem__(self, items):
        return type(self)((k,v) for (k,v) in self.items() if k in items)

With that class definition (assuming it's in multorddict.py) you can do something like this:

>>> from multorddict import MultOrderedDict
>>> mod = MultOrderedDict(banana=3, apple=4, pear=1, orange=2)
>>> mod['apple', 'banana']
MultOrderedDict([('banana', 3), ('apple', 4)])
>>>