Trim an ordered dict to the last x items
Question: I'm trying to trim an ordered dict to the last x items.

I have the following code, which works but doesn't seem very pythonic.

Is there a better way of doing this?

    
    
    import collections
    d = collections.OrderedDict()
    # SNIP: POPULATE DICT HERE!
    d = collections.OrderedDict(d.items()[-3:])
    


Answer: If you wish to trim the dictionary in place, then you can pop the offending
items:

    
    
    for k in d.keys()[:-3]:
        d.pop(k)
    

(On python 3, you'll need to convert `.keys()` to a list).

If you're wishing to create a new `OrderedDict`, then its not clear quite what
is "unpythonic" about your current approach.

