[英]Convert nested list to nested dictionary
我正在嘗試轉換嵌套列表:
#stock[symbol,price,amount,side]
stocks = [["AAPL",10,5,0],["AAPL",15,2,1],["AAPL",25,1,1],["AAPL",30,4,0],
["TSLA",10,5,0],["TSLA",15,2,1],["TSLA",25,1,1],["TSLA",30,4,0]]
進入字典,如:
#res = {"symbol":{price:total_amount,price:total_amount}
res = {"AAPL":{10:5,15:2,25:1,30:4},"TSLA":{10:5,15:2,25:1,30:4}}
subdict
計算公式為:
subdict ={}
for s,p,a,side in stocks:
subdict[p] = subdict.get(p,0)+a
股票返回 total_share.eg 如果股票 = [["AAPL",10,3,0],["AAPL",10,3,0]] 應該返回 {"AAPL":{10:6}}
from collections import defaultdict
res = defaultdict(dict)
for stock in stocks:
res[stock[0]][stock[1]] = stock[2]
我使用defaultdict
所以我不需要在分配之前檢查 dict 鍵。
輸出:
{'AAPL': {10: 5, 15: 2, 25: 1, 30: 4}, 'TSLA': {10: 5, 15: 2, 25: 1, 30: 4}}
您可以使用itertools.groupby
將共享相同符號的每個子列表收集到一個單獨的迭代器中。
from itertools import groupby
from operator import itemgetter
f = itemgetter(0)
res = {symbol: set(f'{v[1]}:{v[2]}' for v in itr)
for symbol, itr in groupby(sorted(stocks, key=f), f)}
更新為您的評論
#Create result dict
res={}
for list in stocks:
key = list[0]
#Verify if the key are in the dict
if key not in res :
res[key]= {}
#Verify if the 'sub-key' are in the nested-dict
if list[1] not in res[key] :
#if dont, initalizes
res[key][list[1]] = list[2]
else:
#Else sum
res[key][list[1]] += list[2]
查看您的數據,我假設您想要一個字典,其中鍵是每個列表中的第一項,內容是嵌套字典,其中鍵是列表的第二個值,內容是第三個值(第四個和最后一個)值將被忽略)。
我會考慮為此使用defaultdict 。 它將允許您一次性創建所需的數據結構,並具有良好的可讀性。
from collections import defaultdict
stocks = [["AAPL",10,5,0],["AAPL",15,2,1],["AAPL",25,1,1],["AAPL",30,4,0],
["TSLA",10,5,0],["TSLA",15,2,1],["TSLA",25,1,1],["TSLA",30,4,0]]
res = defaultdict(dict)
for symbol, k, v, *rest in stocks:
res[symbol][k] = v
導致
defaultdict(dict,
{'AAPL': {10: 5, 15: 2, 25: 1, 30: 4},
'TSLA': {10: 5, 15: 2, 25: 1, 30: 4}})
defaultdict 的操作就像訪問元素的 dict 一樣。 您始終可以通過將其傳遞給dict()
將其轉換為普通 dict
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.