美化列印數位


python模組pprint用於為python中的各種資料物件提供正確的列印格式。 這些資料物件可以表示字典資料型別,甚至可以表示包含JSON資料的資料物件。 在下面的範例中,我們將看到在應用pprint模組之前和應用它之後資料的輸出格式。

import pprint

student_dict = {'Name': 'Tusar', 'Class': 'XII', 
     'Address': {'FLAT ':1308, 'BLOCK ':'A', 'LANE ':2, 'CITY ': 'HYD'}}

print student_dict
print "\n"
print "***With Pretty Print***"
print "-----------------------"
pprint.pprint(student_dict,width=-1)

當執行上面的程式時,得到以下輸出 -

{'Address': {'FLAT ': 1308, 'LANE ': 2, 'CITY ': 'HYD', 'BLOCK ': 'A'}, 'Name': 'Tusar', 'Class': 'XII'}


***With Pretty Print***
-----------------------
{'Address': {'BLOCK ': 'A',
             'CITY ': 'HYD',
             'FLAT ': 1308,
             'LANE ': 2},
 'Class': 'XII',
 'Name': 'Tusar'}

處理JSON資料

Pprint還可以通過將JSON資料格式化為更易讀的格式來處理它們。

import pprint

emp = {"Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
   "Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],   
   "StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
      "7/30/2013","6/17/2014"],
   "Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"] }

x= pprint.pformat(emp, indent=2)
print x

當執行上面的程式時,得到以下輸出 -

{ 'Dept': [ 'IT',
            'Operations',
            'IT',
            'HR',
            'Finance',
            'IT',
            'Operations',
            'Finance'],
  'Name': ['Rick', 'Dan', 'Michelle', 'Ryan', 'Gary', 'Nina', 'Simon', 'Guru'],
  'Salary': [ '623.3',
              '515.2',
              '611',
              '729',
              '843.25',
              '578',
              '632.8',
              '722.5'],
  'StartDate': [ '1/1/2012',
                 '9/23/2013',
                 '11/15/2014',
                 '5/11/2014',
                 '3/27/2015',
                 '5/21/2013',
                 '7/30/2013',
                 '6/17/2014']}