0

I am designing a dictionary from a string, but I have noticed that after using 'ast.literal_eval()' on python 2.7, my dictionary sequence changes. The good thing is that the values designated to the keys follow suit. I just wanted to know why it does this. Here is a snippet of my code that should be able to run:

import ast

Medication = ["{'A': 3, 'B': 10, 'C': 0, 'D': 3}"]
print "Medication before ast.literal_eval: ", Medication[0]
print ""
dictionaryDose = ast.literal_eval(Medication[0])
print "Medication after ast.literal_eval: ", Medication[0]
print ""
print "DictionaryDose: ", dictionaryDose

Here is the output:

Medication before ast.literal_eval: {'A': 3, 'B': 10, 'C': 0, 'D': 3}

Medication after ast.literal_eval: {'A': 3, 'B': 10, 'C': 0, 'D': 3}

DictionaryDose: {'A': 3, 'C': 0, 'B': 10, 'D': 3}

Community
  • 1
  • 1
  • 6
    Dictionaries are unordered containers. You should not rely on them being in any particular order. – khelwood Feb 08 '18 at 10:15
  • If order is important, you can check the answers to this question https://stackoverflow.com/questions/2703599/what-would-a-frozen-dict-be – zezollo Feb 08 '18 at 10:20
  • If you don't care about the order except when printed on screen, try the pretty print `pprint` module. – VPfB Feb 08 '18 at 10:28

2 Answers2

0

Dictionaries are unordered. If you want to keep the order you can use the json module and collections.OrderedDict. You will have to convert single quotes to double quotes before you do this though:

Medication = "{'A': 3, 'B': 10, 'C': 0, 'D': 3}"
Medication = Medication.replace("'", '"')

print json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(Medication)

Output: OrderedDict([(u'A', 3), (u'B', 10), (u'C', 0), (u'D', 3)])

Farhan.K
  • 3,425
  • 2
  • 15
  • 26
0

Use collections.OrderedDict. Just note for python 2.7, use .iteritems() instead of .items().

from collections import OrderedDict
import ast

Medication = ["{'A': 3, 'B': 10, 'C': 0, 'D': 3}"]
print("Medication before ast.literal_eval: ", Medication[0])
print("")
dictionaryDose = ast.literal_eval(Medication[0])
print("Medication after ast.literal_eval: ", Medication[0])
dictionaryDoseOrdered = OrderedDict([(k,v) for k,v in dictionaryDose.items()])
print("")
print("DictionaryDose: ", dictionaryDoseOrdered)
jpp
  • 159,742
  • 34
  • 281
  • 339