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?
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?
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')
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.