1

With python 2.x we can do this:

>>> d = {0:'foo', 1:'bar'}
>>> d.keys()
[0, 1]
>>> d.keys()[0]
0
>>> d.values()
['foo', 'bar']
>>> d.values()[0]
'foo'

With python 3.x, .keys() return dict_key and .values() return dict_value. I guess these view objects are most performant than direct list render in python 2.x (like generator ?).

But, to access dict key/dict value by index we have to use list():

>>> d = {0:'foo', 1:'bar'}
>>> d.keys()
dict_keys([0, 1])
>>> d.values()
dict_values(['foo', 'bar'])
>>> list(d.values())[0]
'foo'
>>> list(d.keys())[0]
0

Is there a way to access them by index (0, 1, [...] 999] without make a complete list() of keys/values to access one index ? (I work with very big dictionnary)

This question is about performance. Not about how to do it. Duplicate flag is not pertinant.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
bux
  • 7,087
  • 11
  • 45
  • 86
  • `next(iter(d))` or `next(iter(d.values()))`. – Martijn Pieters Feb 27 '15 at 16:37
  • you can convert to an iterator then use `next` , `>>> next(iter(d.keys())) 0` – Mazdak Feb 27 '15 at 16:37
  • Those view objects exist because they provide a “view” to the dictionary’s internal representation of the keys and values. So if the dictionary internally uses something other than lists (which is the case), then you don’t have the overhead of having to create an in-memory list of all the keys/values. – poke Feb 27 '15 at 16:38
  • My question is about access an index, not only '0'. @poke: thx ! – bux Feb 27 '15 at 16:39
  • 1
    If you need to access the dictionary at multiple indexes, then store the indexes in a (sorted) list, and enumerate through the views. Then, when you hit an index you care for, stop and do the stuff with the value. – poke Feb 27 '15 at 16:41
  • @poke i see i can gain or lose perf: http://pastebin.com/PT28xqRS maybe i can determine where is the middle. – bux Feb 27 '15 at 17:02
  • Why do you want to access a dictionary by index? This is normally not the way, how you work with dictionaries. – Daniel Feb 27 '15 at 17:06
  • @poke (seems to be most perf when index is under 10%. http://pastebin.com/0xVTya0Q ) – bux Feb 27 '15 at 17:16
  • @Daniel Hi, it's related to http://stackoverflow.com/a/28760992/801924 – bux Feb 27 '15 at 17:17
  • @bux: so the answer is, use numpy arrays instead of dictionaries. You don't need to store your information twice. – Daniel Feb 27 '15 at 17:24
  • @Daniel i see a little what you say. So, in http://stackoverflow.com/a/28760992/801924 , how to store "pheromones" in numpy array, and do the same goal that this answer ? – bux Feb 27 '15 at 18:02

0 Answers0