首页 > 解决方案 > 如何打印字符串列表字典

问题描述

我有一本整数列表词典。我想遍历每个字典并生成一个表,其中 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)是固定的。(简表中的效果是可选的,可以没有它!)。

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

标签: pythondictionaryprinting

解决方案


编辑:

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

# 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()

推荐阅读