pythonpandasdictionaryprintingpprint

python: print multiple dictionaries and strings line by line


I have a dataframe with various columns and i have calculated the value_counts for each column and converted them to_dict. i would like to now print them line by line with an addition of a some strings that describes each dictionary as follows:

print( 'Names and counts',
       '\n',
       df['names'].value_counts()[:3].to_dict(),
       '\n',
       'Last names and counts',
       '\n',
       df['last names'].value_counts()[:3].to_dict(),
       'Staff names and counts',
       '\n',
       df['staff_names'].value_counts()[:3].to_dict(),
       '\n',
       'Staff last names and counts',
       '\n',
       df['staff last names'].value_counts()[:3].to_dict())

Current output:
 Names and counts
{"Jack": 20, "John": 10, "Samuel": 9}

 Last names and counts
{"Brown": 25, "Smith": 30, "Jackson": 5}

 Staff names and counts
{"Mars": 22, "Joshua": 20, "Simon": 8}

 Staff last names and counts
{"Bernard": 27, "Kohlen": 16, "Dimun": 7}

so I would like the output to look as follows:

Desired output:

 Names and counts
{"Jack": 20,
 "John": 10,
 "Samuel": 9}

 Last names and counts
{"Brown": 25,
 "Smith": 30,
 "Jackson": 5}

 Staff names and counts
{"Mars": 22,
 "Joshua": 20,
 "Simon": 8}

 Staff last names and counts
{"Bernard": 27,
 "Kohlen": 16,
 "Dimun": 7}

I have tried pprint() instead or print() but that throws an error.

I also tried adding print(*each dictionary, sep= '\n') but it only returns the index and deletes the numbers(counts)


Solution

  • Try this,

    import json
    print( 'Names and counts',
           '\n',
           json.dumps(df['names'].value_counts()[:3].to_dict(),indent=2),
           '\n',
           'Last names and counts',
           '\n',
           json.dumps(df['last names'].value_counts()[:3].to_dict(),indent=2),
           'Staff names and counts',
           '\n',
           json.dumps(df['staff_names'].value_counts()[:3].to_dict(),indent=2),
           '\n',
           'Staff last names and counts',
           '\n',
           json.dumps(df['staff last names'].value_counts()[:3].to_dict(),indent=2)
    

    Change indent parameter to a higher number for better formatting..

    Note: Tested by Creator and working fine.