【问题标题】:How to return dictionary with each result printed on a new line using Python?python - 如何使用Python将每个结果打印在新行上返回字典?
【发布时间】:2024-04-30 23:15:03
【问题描述】:

我正在尝试将我的字典打印在新的一行上,如下所示:

    {"less than high school":0.10202002459160373,
    "high school":0.172352011241876,
    "more than high school but not college":0.24588090637625154,
    "college":0.47974705779026877}

但我编写的代码打印的输出如下所示:

{'less than high school': 0.10202002459160373, 'high school': 0.172352011241876, 'more than high school but not college': 0.24588090637625154, 'college': 0.47974705779026877}

我正在考虑添加一个正则表达式,但我不确定在这里是否合适。任何建议将不胜感激!

def proportion_of_education():
    # importing pandas as pd
    import pandas as pd

    # importing numpyt as np
    import numpy as np

    # reading csv file as a pandas dataframe (df)
    df = pd.read_csv("assets/NISPUF17.csv", index_col=0)

    # pulling values in variable EDUC1
    m_educ=df['EDUC1']

    # sorting through EDUC1 values
    m_val=np.sort(m_educ.values)

    # defining dictionary
    dict={"less than high school":0,
          "high school":0,
          "more than high school but not college":0,
          "college":0
           }

    # equation for defining proportion 
    tot = len(m_val)

    # applying conditions
    dict["less than high school"]=np.sum(m_val==1)/tot
    dict["high school"]=np.sum(m_val==2)/tot
    dict["more than high school but not college"]=np.sum(m_val==3)/tot
    dict["college"]=np.sum(m_val==4)/tot

# printing dict to display proportion results
    print (dict)
    return proportion_of_education()
    raise NotImplementedError()
    
proportion_of_education()

【问题讨论】:

    标签: python-3.x pandas numpy csv dictionary


    【解决方案1】:

    两种方式:

    1 - 遍历您的 dict 并打印每个键/值

    for item in myDict.items():
        print(*item)
    

    输出:

    less than high school 0.10202002459160373
    high school 0.172352011241876
    more than high school but not college 0.24588090637625154
    college 0.47974705779026877
    

    或类似(将项目解包为键/值):

    for key, value in t.items():
        print(f"{key}: {value}")
    

    输出:

    less than high school: 0.10202002459160373
    high school: 0.172352011241876
    more than high school but not college: 0.24588090637625154
    college: 0.47974705779026877
    

    2 - 利用 python 库 pprint,它有一个 pformat 内置方法

    from pprint import pformat
    print(pformat(myDict))
    

    输出:

    {'college': 0.47974705779026877,
     'high school': 0.172352011241876,
     'less than high school': 0.10202002459160373,
     'more than high school but not college': 0.24588090637625154}
    

    如果顺序很重要:

    print(pformat(myDict, sort_dicts=False))
    

    【讨论】:

    最近更新 更多