【问题标题】:How to print dictionary of lists of strings如何打印字符串列表字典
【发布时间】:2020-01-31 22:24:34
【问题描述】:

我有一本整数列表字典。我想遍历每个字典并生成一个表,其中 y 轴设置为列表名称,x 轴设置为任意名称。

a = {'john': {'alex': [5, 6], 'bono': [0, 4]}, 'jane': {'alex': [0, 1], 'bono': [0, 1]}}

for k, v in a.items():
    print('\n' + k)
    for k, v in v.items():
        print(k, v)

当前输出为:

john
alex [5, 6]
bono [0, 4]

jane
alex [0, 1]
bono [0, 1]

我想要的输出是:

john   col1 col2
alex   5    6
bono   0    4

jane | col1 col2
-----------------
alex | 0    1
bono | 0    1

列数(col1 和 col2)是固定的。 (简表中的效果是可选的,可以没有它!)。

编辑:我正在寻找非熊猫(导入模块)解决方案。

【问题讨论】:

    标签: python dictionary printing


    【解决方案1】:

    编辑:

    我已将 pandas 代码保留在下方,以供您参考。 否则,这是一个带有字符串格式的脚本,用于打印您要求的表格。您可以尝试使用数字来使脚本适合更长的名称,如下例所示:

    # your original data:
    outer_name_dictionary = {'john': {'alexis': [5, 6], 'bonofide': [0, 4]}, 'jane doe': {'alex': [0, 1], 'bono': [0, 1]}}
    
    # iterate over each outer dictionary:
    for key, value in outer_name_dictionary.items():
    
        # get inner dictionary:
        inner_name_dictionary = value
    
        # print the column headers, you can change the '10' to a larger number ...
        # but do the same with the print function below:
        print('%10s | col0  col1' %key)
        print(' '*6 + '-'*18)
    
        # iterate over ech inner dictionary:
        for inner_key, inner_value in inner_name_dictionary.items():
    
            # print the column values:
            print('%10s | %4d  %4d' %(inner_key, inner_value[0], inner_value[1]))
    
        print()
    

    输出:

          john | col0  col1
          ------------------
        alexis |    5     6
      bonofide |    0     4
    
      jane doe | col0  col1
          ------------------
          alex |    0     1
          bono |    0     1
    

    熊猫解决方案:

    import pandas as pd
    
    # your original data:
    name_dictionary = {'john': {'alex': [5, 6], 'bono': [0, 4]}, 'jane': {'alex': [0, 1], 'bono': [0, 1]}}
    
    # iterate over each inner dictionary:
    for name in name_dictionary:
    
        # convert each inner dictionary to a dataframe:
        name_dataframe = pd.DataFrame(name_dictionary[name])
    
        # transpose dataframe:
        name_dataframe = name_dataframe.T
    
        # assign original name to name of columns in dataframe:
        name_dataframe.columns.name = name
    
        # rename columns:
        name_dataframe = name_dataframe.rename(columns={
                0 : 'col0',
                1 : 'col1',
        })
    
        # print results:
        print(name_dataframe)
        print()
    

    【讨论】:

    • 谢谢丹尼尔。我正在寻找非熊猫解决方案(编辑描述)。如果没有其他选择,将接受您的回答。
    • 如果你想添加一个(未要求的)pandas 解决方案,你应该考虑df = pd.DataFrame(name_dictionary); print(df.T.stack().apply(pd.Series))
    【解决方案2】:

    嗯,你已经很接近了。您所缺少的只是列标题并解压缩每个列表:

    for head, d in a.items():
        print(head, "col1", "col2", sep='\t')
        for name, lst in d.items():
            print(name, *lst, sep='\t')
    

    这给出了您的示例字典:

    john    col1    col2
    alex    5   6
    bono    0   4
    jane    col1    col2
    alex    0   1
    bono    0   1
    

    为了更整齐的对齐,您可以使用 f-strings:

    cell_size = 6
    for head, d in a.items():
        print(f"{head:{cell_size}} {'col1':{cell_size}} {'col2':{cell_size}}")
        for name, lst in d.items():
            print(f"{name:{cell_size}} {lst[0]:<{cell_size}} {lst[1]:<{cell_size}}", end='')
    

    现在给出:

    john   col1   col2  
    alex   5      6      
    bono   0      4      
    jane   col1   col2  
    alex   0      1      
    bono   0      1     
    

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2015-10-03
      • 1970-01-01
      • 2022-11-04
      • 2020-07-01
      • 2018-01-13
      相关资源
      最近更新 更多