Search code examples
pythonordereddictionary

print up to or from nth key OrderedDict() python


How can i print the first 10 or last 10 key, value pairs of an OrderedDict in python?

this

for item in my_ordereddict[:5]:
    print item

or this:

for i in range(0, 5):
    print my_ordereddict[i]

dont work. Any help?


Solution

  • from collections import OrderedDict
    
    
    if __name__ == '__main__':
        od = OrderedDict([["one", 1], ["two", 2], ["three", 3], ["four", 4], ["five", 5], ["six", 6]])
        for i in od.keys()[0:3]:
            print od[i]