Reputation: 63
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
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
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
Reputation: 47
Keep it simple.
from collections import OrderedDict
x = OrderedDict('test1'='a', 'test2'='b')
print(list(x.keys().index('test1'))
Upvotes: 2
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, OrderedDict
s are pretty small.)
Both versions will work for any iterable; there's nothing special about OrderedDict
here.
Upvotes: 1
Reputation: 49812
If you take the keys as a list, you can then index like:
list(x).index('b')
from collections import OrderedDict
x = OrderedDict(a=1, b=2)
print(list(x).index('b'))
1
Upvotes: 0