Search code examples
pythondictionaryordereddictionarypprint

Using pprint for OrderedDicts when dict is made with two lists


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

Solution

  • 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.