2

I'm trying to print an ordered dictionary using OrderedDict, but when I print it, "OrderedDict" also prints. FYI this is just a code segment, not the whole code. What can I do to fix this? I'm using Python 3.2

Looks like this:

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

And I'm getting this in the text file to which this is writing:

('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)])

Thanks!

mzjn
  • 48,958
  • 13
  • 128
  • 248
  • You know that in your example the order of the output of `dictInfo` is UNORDERED since you first create a regular dict before you create an `OrderedDict` from that, right? – dawg Jun 01 '17 at 17:13

2 Answers2

5

You have several options.

You can use a list comprehension and print that:

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

Or, knowing that the order may change, you can just convert to a dict if you want that output:

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

(With Python 3.6, a regular dict does maintain order. Use Python 3.6 and the order will not change. That is likely going to be the case in the future, but not yet guaranteed.)

Finally, you can subclass OrderDict and replace the __str__ method with a format that you want:

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')

(Change the __repr__ method if you want the output of the repr to be different...)


Final note:

With this:

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

You are actually getting an UNORDERED dict result since you are creating the OrderedDict from a dict literal which is unordered.

You would want to do instead:

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
dawg
  • 98,345
  • 23
  • 131
  • 206
0

If you don't care about the order, just print dict(YourOrderedDict), if you care about the order you can :

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

Hoping it helps

hugoShaka
  • 4,977
  • 3
  • 17
  • 29