Python dictionary: are keys() and values() always

2018-12-31 20:10发布

It looks like the lists returned by keys() and values() methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods).

For example:

>>> d = {'one':1, 'two': 2, 'three': 3}
>>> k, v = d.keys(), d.values()
>>> for i in range(len(k)):
    print d[k[i]] == v[i]

True
True
True

If you do not alter the dictionary between calling keys() and calling values(), is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.

标签: python
8条回答
何处买醉
2楼-- · 2018-12-31 20:58

Yes. Starting with CPython 3.6, dictionaries return items in the order you inserted them.

The documentation hasn't been updated yet, ignore the part that says this is an implementation detail. This is already guaranteed in CPython 3.6 and will be required for all other Python implementations starting with Python 3.7.

查看更多
梦该遗忘
3楼-- · 2018-12-31 21:02

Yes, what you observed is indeed a guaranteed property -- keys(), values() and items() return lists in congruent order if the dict is not altered. iterkeys() &c also iterate in the same order as the corresponding lists.

查看更多
登录 后发表回答