Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Python dictionaries are executed?

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?

like image 937
yondu_udanta Avatar asked Dec 18 '22 08:12

yondu_udanta


1 Answers

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')
like image 125
Vlad Avatar answered Dec 20 '22 21:12

Vlad