OrderedDict in python 3 - how to get the keys in order?

怎甘沉沦 提交于 2019-12-10 13:35:58

问题


In python 2 when using an OrderedDict I was able to get the keys in the order they were inserted by simply using the keys method that returned a list. In python 3 however:

rows = OrderedDict()
rows[0]=[1,2,3]
rows[1]=[1,2,3]
image = [rows[k] for k in rows.keys()[:2]]

I get:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'odict_keys' object is not subscriptable

I certainly can do list(rows)[:2] as advised for instance here - but is this guaranteed to get me the keys in order ? Is this the one right way ?

UPDATE: the python 2 code would be better as:

image = [v for v in rows.values()[:2]]

which of course still blows with the same error on python 3


回答1:


@mglison is right. Because OrderedDict follows the iterator protocol, it is guaranteed to yield the keys in the correct order to list():

However, like @mglison also mentioned,itertools.islice() would be better and more efficent than simply using list and subscripting. After timing both methods multiple times using the timeit module, the itertools method was roughly 2x faster. Here are the exact numbers:

After getting the average time of running both list(itertools.islice(rows, 2)) and list(rows.keys())[:2](notice I'm casting the result of islice() to a list) multiple times, it appears that using the latter method is actual slightly faster:

---------------------------------------------------------------
|  list(itertools.islice(rows, 2))   |    1.5023668839901838  |      
---------------------------------------------------------------
|  list(rows.keys())[:2]             |    1.495460570215706   |      
---------------------------------------------------------------

However, the difference of the two numbers is so small, I really would not make much of difference which method you use. Just choose the method which is the most readable and understandable for your specific case.



来源:https://stackoverflow.com/questions/44147047/ordereddict-in-python-3-how-to-get-the-keys-in-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!