XiaoXiao
XiaoXiao

Reputation: 63

python OrderedDict get a key index of

Can OrderedDict get a key position?

is like list of index()

test = ['a', 'b', 'c', 'd', 'e']
test.index('b') # return 1

Upvotes: 2

Views: 8769

Answers (5)

Conchylicultor
Conchylicultor

Reputation: 5729

The accepted answer list(x).index('b') will be O(N) every time you're searching for the position.

Instead, you can create a mapping key -> position which will be O(1) once the mapping is constructed.

ordered_dict = OrderedDict(a='', b='')

key_to_pos = {k: pos for pos, k in enumerate(ordered_dict)}
assert key_to_pos['b'] == 1

Upvotes: 0

Karl Doenitz
Karl Doenitz

Reputation: 2230

just one line program. such as:

print(list(your_ordered_dict).index('your_key'))

Maybe you can use lambda,like this line program:

f = lambda ordered_dict, key: list(ordered_dict).index(key)

Good luck.

Upvotes: 7

Idhant Haldankar
Idhant Haldankar

Reputation: 47

Keep it simple.

from collections import OrderedDict

x = OrderedDict('test1'='a', 'test2'='b')
print(list(x.keys().index('test1'))

Upvotes: 2

abarnert
abarnert

Reputation: 365925

You can write this in two ways:

  • list(x).index('b')
  • next(i for i, k in enumerate(x) if k=='b')

The first one will be a little faster for small dicts, but a lot slower, and waste a lot of space, for huge ones. (Of course most of the time, OrderedDicts are pretty small.)

Both versions will work for any iterable; there's nothing special about OrderedDict here.

Upvotes: 1

Stephen Rauch
Stephen Rauch

Reputation: 49812

If you take the keys as a list, you can then index like:

Code:

list(x).index('b')

Test Code:

from collections import OrderedDict

x = OrderedDict(a=1, b=2)
print(list(x).index('b'))

Results:

1

Upvotes: 0

Related Questions