Tabulating data received with json with python

断了今生、忘了曾经 提交于 2020-12-13 03:10:22

问题


I can parse the following data. but I cannot show it as a table in columnar. How can I chart this?

 for item in items:
     print(item['symbol'])
[
{"symbol": "ZILUSDT", "positionAmt": "0", "entryPrice": "0.00000", "markPrice": "0.01728152", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "20", "maxNotionalValue": "25000", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "SHORT"}, 
{"symbol": "FLMUSDT", "positionAmt": "0", "entryPrice": "0.0000", "markPrice": "0.00000000", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "20", "maxNotionalValue": "25000", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "BOTH"}, 
{"symbol": "FLMUSDT", "positionAmt": "0", "entryPrice": "0.0000", "markPrice": "0.00000000", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "20", "maxNotionalValue": "25000", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "LONG"}, 
{"symbol": "FLMUSDT", "positionAmt": "0", "entryPrice": "0.0000", "markPrice": "0.00000000", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "20", "maxNotionalValue": "25000", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "SHORT"}
]



How can I show it in a table like the one below?

     headers = ["Symbol", "EntryPrice", "side", "position"]
     symbols = [x['symbol'] for x in data]
     table = columnar(symbols, headers=headers)
     print(table)

回答1:


You have a list of dictionaries. The easiest way is to wrap them into pandas' DataFrame, which handles that type out-of-the box.

import pandas as pd

tabulated = pd.DataFrame(items)
print(tabulated)



回答2:


Pandas is an excellent solution, but you can natively present data in table format too:

for row in zip(*([key] + (value) for key, value in sorted(items.items()))):
    print(*row)


来源:https://stackoverflow.com/questions/64612074/tabulating-data-received-with-json-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!