繁体   English   中英

在矩阵中打印嵌套字典 - python

[英]Printing a nested dictionary in a matrix - python

寻找一种将嵌套字典打印为矩阵的方法:

输入

nestedD ={'h1': {r1: float1, r2: float2, r3: float3}, 'h2': {r1: float4, r2: float5, r3: float6}, 'h3': {r1: float7, r2: float8, r3: float9}}
Output
|    |    h1    |    h2    |    h3   |
| -- | -------- | -------- | ------- |
| r1 | float1   | float4   | float7  |
| r2 | float2   | float5   | float8  |
| r3 | float3   | float6   | float9  |

在此处输入图像描述

到目前为止,我有这个:

for h, innerD in nestedD.items():
            print (h)
            for r in innerD:
                print("{: >10} {: >10} {: >10}".format(*innerD[r]))
                

TypeError:*后的格式()参数必须是可迭代的,而不是浮点数

如何使用 format() 遍历内部字典的浮点数?

for h, innerD in nestedD.items():
            print (h)
            print("{: >10} {: >10} {: >10}".format(*innerD.values()))

因此,您收到错误的原因是innerD[r]解析为地址nestedD[h][r]处的数字。 星号将您可以迭代的内容(如列表)作为参数列表传递给 function。 由于您有 3 种格式 arguments,因此应使用 3 种 arguments 传递格式。 在上面的更新代码中,三个 arguments 来自内部字典的值。

再次阅读您的问题,似乎仍然不是您想要的。 看来您想先对字典进行一种轮换。 上面的答案将错误地排序值。

print("|__| {} | {} | {} |".format(*nestedD.keys()))
headers = nestedD.keys()
# There is an assumption here that all the inner dictionaries have the same keys
rows = nestedD.values[0].keys() 
rotatedD = dict([(row,dict([(header, nestedD[header][row]) for header in headers])) for row in rows])
for key, values in rotatedD:
    str_values = "|".join(["{: >10}".format(v) for v in values])
    print("|{key}|{values}|".format(key=key, values=str_values))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM