S Andrew
S Andrew

Reputation: 7268

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

Upvotes: 0

Views: 3010

Answers (3)

Artiom  Kozyrev
Artiom Kozyrev

Reputation: 3836

You can get only keys or keys and values the following ways below, also I suppose that array instances should have been created differently, array should have elements of the same type and type of the elemnts should be declared beforehand:

array module

from collections import OrderedDict
from array import array

# right way to create array instance is to specifu array type:
x = OrderedDict([(0, array('I', [308, 186])), (2, array('I', [431, 166]))])  

for k in x.keys():  # print all keys
    print(k)

for k, v in x.items():  # print key and value
    print("{}___{}".format(k, v))

Upvotes: 2

James Bear
James Bear

Reputation: 444

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.

Upvotes: 4

Skycc
Skycc

Reputation: 3555

you can get output you want through dict.items()

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

alternatively, you can get the dict keys() through dict.keys()

odict.keys() will return you [0,2]

Upvotes: 0

Related Questions