Noa*_*hof 1 python dictionary ordereddictionary python-3.x
我正在尝试使用 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
Run Code Online (Sandbox Code Playgroud)
我在写入的文本文件中得到了这个:
('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)])
Run Code Online (Sandbox Code Playgroud)
谢谢!
您有多种选择。
您可以使用列表理解并打印:
>>> od
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
>>> [(k,v) for k,v in od.items()]
[('one', 1), ('two', 2), ('three', 3)]
Run Code Online (Sandbox Code Playgroud)
或者,知道顺序可能会改变,如果你想要输出,你可以转换为 dict:
>>> dict(od)
{'one': 1, 'two': 2, 'three': 3}
Run Code Online (Sandbox Code Playgroud)
(使用 Python 3.6,常规dict 会维护 order。使用 Python 3.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')
Run Code Online (Sandbox Code Playgroud)
(__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
Run Code Online (Sandbox Code Playgroud)
你实际上得到了一个 UNORDERED 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
Run Code Online (Sandbox Code Playgroud)