1

When I have OrderedDict created from two list and if I try to use pprint it's not working as expected, bur it works fine if I create OrderedDict normally.

Any additional steps needs to be taken to get expected output of each key value in separate line if OrderedDict is created with two list ?

import pprint
from collections import OrderedDict

pprint does not work

l1 = [ 'a', 'b', 'x', 'd']
l2 = [ ['abc', 'def'], ['idk', 'jfk'], ['mnp'], ['oye oye']]
dic = OrderedDict(zip(l1, l2))
pprint.pprint(dic, width = 1)

OrderedDict([('a', ['abc', 'def']), ('b', ['idk', 'jfk']), ('x', ['mnp']), ('d', ['oye oye'])])

Works !!!

dic2 = OrderedDict()
dic2 = {'a': 'abc', 'x' : 'xyz', 'b' : 'boy'}
pprint.pprint(dic2, width = 1)

{'a': 'abc',
 'b': 'boy',
 'x': 'xyz'}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
oneday
  • 629
  • 1
  • 9
  • 32

1 Answers1

1

In the version that you think works, you are not printing a OrderedDict, but an ordinary dict. See that dic2 = {'a': 'abc', 'x' : 'xyz', 'b' : 'boy'} is an ordinary dict.

To create a OrderedDict from a dict you should have written:

dic2 = OrderedDict({'a': 'abc', 'x' : 'xyz', 'b' : 'boy'})

an the result would be the same as the zip version.

It seems that Python 2.7 doesnt support pprint from OrderedDict, see here for some workarounds.

Community
  • 1
  • 1
malbarbo
  • 10,717
  • 1
  • 42
  • 57
  • ahh - I got it . I saw the post you mentioned but since it was 5 yrs back I thought bug would be fixed, anyways thanks for the pointer .. I would follow that link ..appreciate your help !! – oneday May 16 '16 at 21:13