def key(): print 'key'
def val(): print 'val'
{key() : val()}
prints val, key
, i.e. the value is evaluated first. Is this behaviour
Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.
Dictionary literals. A dictionary literal can contain one or more pairs of key/item values. The first expression in a dictionary literal entry is the key value and the second expression is the item value. In a dictionary literal, all key values must be the same type and all item values must the same type.
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair.
Dictionaries do not have a predictable order as their keys are stored by a hash. If you need order, use a list or collections.
This section of the reference manual documents the order, but claims it is different than what you are seeing: http://docs.python.org/2/reference/expressions.html#evaluation-order
In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:
expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2
And there is an open bug against the implementation about it: Evaluation order of dictionary display is different from reference manual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With