Search code examples
pythonordereddictionary

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.


Solution

  • 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 items(self, *items):
            all = super(MultOrderedDict, self).items()
            if not items:
                return all
            return type(self)((key, value) for (key, value) in all if key in items).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.items()
    [('orange', 2), ('pear', 1), ('apple', 4), ('banana', 3)]
    >>> mod.items('apple','banana')
    [('apple', 4), ('banana', 3)]
    >>> 
    

    This approach changes the semantics of the items method, which might not be such a good thing.