1

Order of my dictionary is changed when using ast.literal_eval() function. Following is my program,

dicty="{'@#$':'Please enter a valid Email Address.','testuser1009131@,$%^*&@!$)(:;gmail.com':'Please enter a valid Email Address.','am@am.pm':'None'}"
dictionary=ast.literal_eval(dicty)
print dictionary

My Output:

{'testuser1009131@,$%^*&@!$)(:;gmail.com': 'Please enter a valid Email Address.', 'am@am.pm': 'None', '@#$': 'Please enter a valid Email Address.'}

Expected Output:

{'@#$':'Please enter a valid Email Address.','testuser1009131@,$%^*&@!$)(:;gmail.com':'Please enter a valid Email Address.','am@am.pm':'None'}
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • python dictionaries are not ordered ... Unfortunately, to get this in order, you'd need to write your own parser or convert the input format to `json` where you can parse via `json.loads` and supply `object_pairs_hook=collections.OrderedDict`... – mgilson Jul 27 '16 at 07:08
  • Dicts only represent "does this key have a value associated" and "if so, what value?". They do not represent any sort of ordering of the key-value associations they store. – user2357112 Jul 27 '16 at 07:08
  • Confirmed this behavior in Python2.7, but this python version will be depreciated very soon. And, I tested on Python3.6, the order of your input is reserved. – weefwefwqg3 Oct 31 '19 at 00:25

0 Answers0