Python 如何打印字符串列表字典
我有一本INT列表字典。我希望遍历每个字典,并生成一个表,其中y轴设置为list name,x轴设置为任意名称Python 如何打印字符串列表字典,python,dictionary,printing,Python,Dictionary,Printing,我有一本INT列表字典。我希望遍历每个字典,并生成一个表,其中y轴设置为list name,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 a
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
我期望的输出是:
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)是固定的。(Jane表中的效果是可选的,没有它也可以使用!)
编辑:我正在寻找非熊猫(导入模块)解决方案。编辑:
我在下面留下了熊猫的代码,以防你想引用它。
否则,这里有一个带有字符串格式的脚本,用于打印所需的表。您可以尝试使用数字使脚本适合较长的名称,如本例所示:
# 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()
嗯,你很接近。您所缺少的只是列标题和解压缩每个列表的步骤:
对于头部,a.项目()中的d:
打印(打印头,“col1”,“col2”,sep='\t')
对于名称,d.items()中的lst:
打印(名称*lst,sep='\t')
这在您的示例词典中给出:
john col1 col2
alex 5 6
bono 0 4
jane col1 col2
alex 0 1
bono 0 1
为了使排列更整齐,您可以使用f弦:
cell\u size=6
对于头部,a.items()中的d:
打印(f“{head:{cell_size}}{'col1':{cell_size}}{'col2':{cell_size}}”)
对于名称,d.items()中的lst:
打印(F){名称:{CyLyStase}}{LST(0):谢谢丹尼尔。我正在寻找非熊猫解决方案(编辑说明)。如果没有添加任何替代方案,将接受您的答案。如果您想添加(未请求的)熊猫解决方案,您应该考虑<代码> DF= Pd。DataFrame(NAMEYONGROUP);打印(DF.T.STACKE)(应用(PD系列))< /代码>。