43

I would like to get the value by key index from a Python dictionary. Is there a way to get it something like this?

dic = {}
value_at_index = dic.ElementAt(index)

where index is an integer

E_net4 - Krabbe mit Hüten
  • 24,143
  • 12
  • 85
  • 121
Dmitry Dyachkov
  • 1,515
  • 2
  • 16
  • 43

4 Answers4

46

In Python versions before 3.7 dictionaries were inherently unordered, so what you're asking to do doesn't really make sense.

If you really, really know what you're doing, use

value_at_index = list(dic.values())[index]

Bear in mind that prior to Python 3.7 adding or removing an element can potentially change the index of every other element.

amicitas
  • 11,973
  • 4
  • 35
  • 49
NPE
  • 464,258
  • 100
  • 912
  • 987
14

Let us take an example of dictionary:

numbers = {'first':0, 'second':1, 'third':3}

When I did

numbers.values()[index]

I got an error:'dict_values' object does not support indexing

When I did

numbers.itervalues()

to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'

Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.

tuple(numbers.items())[key_index][value_index]

for example:

tuple(numbers.items())[0][0] gives 'first'

if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use

list(list(numbers.items())[index])
10

If you really just want a random value from the available key range, use random.choice on the dictionary's values (converted to list form, if Python 3).

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))
MikeRand
  • 4,550
  • 8
  • 39
  • 61
6

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

user2426679
  • 2,647
  • 1
  • 29
  • 29