【问题标题】:"OrderedDict()" Itself printing when using OrderedDict()使用 OrderedDict() 时“OrderedDict()”本身打印
【发布时间】:2017-06-01 16:40:02
【问题描述】:

我正在尝试使用 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)])

谢谢!

【问题讨论】:

  • 您知道,在您的示例中,dictInfo 的输出顺序是 UNORDERED,因为您首先创建了一个常规 dict,然后再创建一个 OrderedDict,对吧?

标签: python python-3.x dictionary ordereddictionary


【解决方案1】:

您有多种选择。

您可以使用列表推导并打印:

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

或者,知道顺序可能会改变,如果你想要那个输出,你可以转换为一个字典:

>>> dict(od)
{'one': 1, 'two': 2, 'three': 3}

(对于 Python 3.6,一个常规的 dict does maintain 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')

(如果您希望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 结果,因为您是从无序的 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

【讨论】:

    【解决方案2】:

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

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

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2022-07-20
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      相关资源
      最近更新 更多