4

If I run the following code:

a={}
a[input("key: ")] = input("value: ")

The interpreter is first prompting me a value input and then the key input.

What is the reason behind this?

jsbueno
  • 99,910
  • 10
  • 151
  • 209
yondu_udanta
  • 797
  • 1
  • 6
  • 13
  • 3
    From [Simple Statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements) in the Python Docs: "An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right." – Patrick Haugh Apr 12 '17 at 13:29
  • You can also take a look at: [How are Python's Built In Dictionaries Implemented](http://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented) – dot.Py Apr 12 '17 at 13:30

2 Answers2

6

Usually the order of the inner expression is never guaranteed. What happens in your case is that interpreter first finds out what needs to be put into the dictionary, then it finds out where it should be put it. From interpreter's perspective this is more optimal order.

Because something might happen during input('value') call, like an exception or you can simply terminate your program. So why bother with finding out where to put that value until you actually have it.

In cases where you do care about order you should do the following:

key = input('key')
a[key] =  input('value')
dot.Py
  • 5,007
  • 5
  • 31
  • 52
Vlad
  • 9,180
  • 5
  • 48
  • 67
5

From the docs:

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176