Python dictionary: are keys() and values() always the same order?
Found this:
If
items()
,keys()
,values()
,
iteritems()
,iterkeys()
, and
itervalues()
are called with no
intervening modifications to the
dictionary, the lists will directly
correspond.
On 2.x documentation and 3.x documentation.
What ordering does dict.keys() and dict.values() guarantee?
The general rules:
- Before talking about what is guaranteed and what isn't, even if some ordering seems to be "guaranteed", it isn't. You should not rely on it. It is considered bad practice, and could lead to nasty bugs.
d.keys()
,d.values()
, andd.items()
all return the elements in a respective order. The order should be treated as arbitrary (no assumptions should be made about it). (docs)- consecutive calls to
d.keys()
,d.values()
, andd.items()
are "stable", in the sense they are guaranteed to preserve the order of previous calls (assuming no insertion/deletion happens between the calls). - Since CPython's V3.6,
dict
has been reimplemented, and it now preserves insertion order. This was not the goal of the change, but a side effect, and it is NOT part of the python spec, only a detail of the CPython implementation. See point #1 above: relying on this is bad practice and should not be done. Anyways, you should avoid writing CPython-specific code. - In Python2, order is deterministic (i.e. creating a dict twice in the same way will result with the same order). In Python <3.6, it is no longer deterministic, so you can't rely on that either (I'm not sure if this non-determinism is part of the spec or just a CPython implementation detail).
EDIT: added point #5, thanks to @AndyHayden's comment.
Are order of keys() and values() in python dictionary guaranteed to be the same?
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If
items()
,keys()
,values()
,iteritems()
,iterkeys()
, anditervalues()
are called with no intervening modifications to the dictionary, the lists will directly correspond.
From the documentation for dict
.
Related Topics
How to Make Selenium Not Wait Till Full Page Load, Which Has a Slow Script
How to Rotate an Image Around an Off Center Pivot in Pygame
Python:No Module Named Selenium
If Python Is Interpreted, What Are .Pyc Files
How to Convert a Nested Python Dict to Object
Differencebetween a String and a Byte String
How to Hide the Console When I Use Os.System() or Subprocess.Call()
Running Unittest with Typical Test Directory Structure
Is It Worth Using Python's Re.Compile
Creating a Range of Dates in Python
Tkinter.Tclerror: Image "Pyimage3" Doesn't Exist
Importing a CSV File into a SQLite3 Database Table Using Python
Using Pandas to Pd.Read_Excel() for Multiple Worksheets of the Same Workbook
How to Keep Python Print from Adding Newlines or Spaces
Using Quotation Marks Inside Quotation Marks