我正在尝试使用OrderedDict打印有序字典,但是当我打印它时,“OrderedDict”也会打印出来。仅供参考,这只是一个代码段,而不是整个代码。我该怎么做才能解决这个问题?我正在使用Python 3.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
我在写这篇文章的文本中得到了这个:
('snack', 'bananana')OrderedDict([('USA', 'No'), ('Sodium', 119), ('Calories', 479), ('Servings per Container', 7), ('Sugar', 49), ('Saturated Fat', 37.553599999999996), ('Total Fat', 234.71), ('Cholesterol', 87), ('Amount per Serving', 40), ('Fiber', 1), ('Caffeine', 7), ('Protein', 53)])
谢谢!
答案 0 :(得分:4)
您有几种选择。
您可以使用列表推导并打印:
>>> od
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
>>> [(k,v) for k,v in od.items()]
[('one', 1), ('two', 2), ('three', 3)]
或者,知道订单可能会改变,如果你想要输出,你可以转换为dict:
>>> dict(od)
{'one': 1, 'two': 2, 'three': 3}
(使用Python 3.6,常规dict
does maintain order。使用Python 3.6并且顺序不会改变。未来可能会出现这种情况,但尚未得到保证。)< / p>
最后,您可以继承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
实际上,您正在获取UNORDERED 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
答案 1 :(得分:0)
如果您不关心订单,只需打印dict(YourOrderedDict)
,如果您关心订单:
for key, value in yourOrderedDict.items():
print(key, value)
希望有所帮助