我试图用OrderedDict打印一个有序字典,但是当我打印它时,“OrderedDict”也会打印出来。仅供参考,这只是一个代码段,而不是整个代码。我能做些什么来解决这个问题?我使用的是python3.2
看起来像这样:
def returnAllStats(ints):
choices = ["Yes","No"]
dictInfo = {"Calories":ints[2], "Servings per Container":ints[0], "Amount per Serving":ints[1], "Total Fat":(ints[3]/100)*ints[2], "Saturated Fat":(ints[4]/100)*(ints[3]/100)*ints[2], "Cholesterol":ints[5], "Fiber":ints[6], "Sugar":ints[7], "Protein":ints[8], "Sodium":ints[9], "USA":choices[ints[10]], "Caffeine":ints[11]}
dictInfo = collections.OrderedDict(dictInfo)
return dictInfo
我在文本文件中得到了这个,这是要写的:
^{pr2}$谢谢!在
你有几种选择。在
您可以使用列表理解并打印:
或者,知道顺序可能会改变,如果需要输出,可以直接转换为dict:
^{pr2}$(在python3.6中,一个常规的
dict
does maintain order。使用python3.6,顺序不会改变。未来很可能会出现这种情况,但目前还不能保证。)最后,您可以将
OrderDict
子类化,并将__str__
方法替换为所需的格式:(如果希望repr的输出不同,请更改
__repr__
方法…)最后一点:
有了这个:
实际上,您得到的是一个无序的dict结果,因为您是从一个无序的dict文本创建OrderedDict。在
你应该改为:
如果您不关心顺序,只需打印
dict(YourOrderedDict)
,如果您关心顺序,您可以:希望有帮助
相关问题 更多 >
编程相关推荐