简体   繁体   English

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

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

Looking for a way to print a nested dictionary as a matrix:寻找一种将嵌套字典打印为矩阵的方法:

Input输入

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  |

在此处输入图像描述

So far I have this:到目前为止,我有这个:

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

TypeError: format() argument after * must be an iterable, not float TypeError:*后的格式()参数必须是可迭代的,而不是浮点数

How can I iterate through floats of the inner dictionaries using format()?如何使用 format() 遍历内部字典的浮点数?

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

So the reason for the error that you are getting is that innerD[r] resolves to the number at the address nestedD[h][r] .因此,您收到错误的原因是innerD[r]解析为地址nestedD[h][r]处的数字。 The star passes something you can iterate over (like a list) as the list of parameters to the function.星号将您可以迭代的内容(如列表)作为参数列表传递给 function。 Since you have 3 format arguments, format should be passed with 3 arguments.由于您有 3 种格式 arguments,因此应使用 3 种 arguments 传递格式。 In the updated code above the three arguments come from the values of the inner dictionary.在上面的更新代码中,三个 arguments 来自内部字典的值。

Reading through your question again it seems that still isn't quite what you want.再次阅读您的问题,似乎仍然不是您想要的。 It seems you want to do a kind of rotation on the dictionary first.看来您想先对字典进行一种轮换。 The answer above will order the values incorrectly.上面的答案将错误地排序值。

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