“OrderedDict()”本身在使用OrderedDict()时打印

2024-10-03 04:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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}$

谢谢!在


Tags: no代码字典def代码段fatyeschoices
2条回答

你有几种选择。在

您可以使用列表理解并打印:

>>> od
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
>>> [(k,v) for k,v in od.items()]
[('one', 1), ('two', 2), ('three', 3)] 

或者,知道顺序可能会改变,如果需要输出,可以直接转换为dict:

^{pr2}$

(在python3.6中,一个常规的dictdoes maintain order。使用python3.6,顺序不会改变。未来很可能会出现这种情况,但目前还不能保证。)

最后,您可以将OrderDict子类化,并将__str__方法替换为所需的格式:

class Mydict(OrderedDict):
    def __str__(self):
        return ''.join([str((k, v)) for k,v in self.items()])

>>> md=Mydict([('one', 1), ('two', 2), ('three', 3)])   
>>> md     # repr
Mydict([('one', 1), ('two', 2), ('three', 3)])
>>> print(md)
('one', '1')('two', '2')('three', '3')

(如果希望repr的输出不同,请更改__repr__方法…)


最后一点:

有了这个:

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

实际上,您得到的是一个无序的dict结果,因为您是从一个无序的dict文本创建OrderedDict。在

你应该改为:

def returnAllStats(ints):
    choices = ["Yes","No"]
    return collections.OrderedDict([("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])]}
    return dictInfo

如果您不关心顺序,只需打印dict(YourOrderedDict),如果您关心顺序,您可以:

for key, value in yourOrderedDict.items():
    print(key, value)

希望有帮助

相关问题 更多 >