[英]Defining a function to cross-reference variables in 2 dictionaries in python
[英]How to cross-reference two dictionaries in python. So they can print a nice excel-like table
所以我目前有這樣的字典集:
Dict = {'customer1': {datetime.datetime(2017, 6, 15, 14, 34, 55): '12', datetime.datetime(2017, 6, 16, 14, 34, 55): '14'}, 'customer2': {datetime.datetime(2017, 6, 16, 14, 34, 55): '16', datetime.datetime(2017, 6, 17, 14, 34, 55): '18'}}
我要打印的是這樣的:
--------- 15/06/2017 16/06/2017 17/06/2017
customer1 12 14 --
customer2 16 18
我考慮過要創建另一個臨時工。 字典 首先按日期排序,然后再按客戶名稱排序,然后交叉引用這兩個列表。 我確實設法創建了另一個字典。 看起來像這樣:
tempDict = {datetime.datetime(2017, 6, 15, 14, 34, 55): {'customer1': '12'}, datetime.datetime(2017, 6, 16, 14, 34, 55): {'customer1': '14', 'customer2': '16'}, datetime.datetime(2017, 6, 17, 14, 34, 55): {'customer2': '18'}
但是我不知道如何交叉引用這些列表。 總的來說,我還是一個新手。 有什么辦法可以更有效地做到這一點? 我如何使用這種方法? 我目前陷入困境。
def excelLikeTable():
tempDict = {}
for x in dict.keys():
for y, z in dict[x].items():
emptyDict[y] = {}
emptyDict[y][x] = z
print('')
return
除了自己進行格式化外,還有一個名為pandas
的Python庫,該庫具有一些工具來對(2d)表進行正確的格式化。
您可以使用以下命令安裝pandas
:
pip install pandas
(或其他pip
包管理器)。 然后您可以像這樣使用它:
import pandas as pd
df = pd.DataFrame(Dict).T
現在df
是一個dataframe 。 如果print
,您將得到:
>>> print(df)
2017-06-15 14:34:55 2017-06-16 14:34:55 2017-06-17 14:34:55
customer1 12 14 NaN
customer2 NaN 16 18
我猜大概是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.