python:逐行打印多个字典和字符串

问题描述

我有一个包含各种列的数据框,我计算了每列的 value_counts 并将它们转换为_dict。我现在想逐行打印它们,并添加一些描述每个字典的字符串,如下所示:

print( 'Names and counts','\n',df['names'].value_counts()[:3].to_dict(),'Last names and counts',df['last names'].value_counts()[:3].to_dict(),'Staff names and counts',df['staff_names'].value_counts()[:3].to_dict(),'Staff last names and counts',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}

所以我希望输出如下所示:

Desired output:

 Names and counts
{"Jack": 20,"Dimun": 7}

我已经尝试过 pprint() 或 print() 但会引发错误

我也尝试添加 print(*each dictionary,sep='\n') 但它只返回索引并删除数字(计数)

解决方法

试试这个,

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

将缩进参数更改为更高的数字以获得更好的格式..

注意:经创作者测试,工作正常。

,

使用 json.dumpsindent = 字典级别:

for c in df.columns:
    print(f"{c} and counts\n{json.dumps(df[c].value_counts()[:3].to_dict(),indent=2)}")