[英]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.