Search code examples
pythonordereddictionary

How to get the key from OrderedDict in python


I have a below OrderedDict in python:

OrderedDict([(0, array([308, 186])), (2, array([431, 166]))])

Is there any way I can separately get the key and its value something like below:

print(odict[0][0])
print(odict[0][1])
print(odict[1][0])
print(odict[1][1])

so that I get below output

0
array([308, 186])
2
array([431, 166])

but doing above I only get:

308
186
431
166

Is there any way I can extract the keys (0, 1, 2, 3..). Please help. Thanks


Solution

  • There is a way to extract keys:

    odict.keys()
    

    To traverse the dict, you can:

    for key, value in odict.items():
        print(key, value)
    

    These code snippets also work on ordinary dict objects.