Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation order of dictionary literals

def key(): print 'key'
def val(): print 'val'

{key() : val()}

prints val, key, i.e. the value is evaluated first. Is this behaviour

  • consistent across python versions and implementations?
  • documented anywhere? (http://docs.python.org/2/reference/expressions.html#dictionary-displays says nothing)
like image 532
georg Avatar asked Mar 28 '13 11:03

georg


People also ask

What is the order of dictionary in Python?

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.

What are dictionary literals?

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.

Is dictionary an ordered sequence?

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.

Does dictionary store in order?

Dictionaries do not have a predictable order as their keys are stored by a hash. If you need order, use a list or collections.


1 Answers

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.

like image 166
Ned Batchelder Avatar answered Sep 28 '22 00:09

Ned Batchelder