python的ast.literal_eval()改变了我的字典序列

时间:2018-02-08 10:14:52

标签: python python-2.7 dictionary

我正在从字符串设计字典,但我注意到在python 2.7上使用'ast.literal_eval()'后,我的字典序列发生了变化。好处是指定给键的值也是如此。我只是想知道为什么会这样做。以下是我应该能够运行的代码片段:

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

这是输出:

  

ast.literal_eval之前的药物:{'A':3,'B':10,'C':0,'D':3}

     

ast.literal_eval后的药物:{'A':3,'B':10,'C':0,'D':3}

     

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

2 个答案:

答案 0 :(得分:0)

字典无序。如果您想保留订单,可以使用json模块和collections.OrderedDict。在执行此操作之前,您必须将单引号转换为双引号:

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

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

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

答案 1 :(得分:0)

使用collections.OrderedDict。请注意python 2.7,使用.iteritems()代替.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)