簡體   English   中英

從嵌套列表 python 創建嵌套字典

[英]create nested dict from nested list python

我正在嘗試將列表列表轉換為嵌套字典。 嵌套列表如下所示(包含日期的列表列表):

[[11, 'January', 2021],
 [12, 'January', 2021],
 [13, 'January', 2021],
 .
 .
 .
 [13, 'June', 2022],
 [14, 'June', 2022],
 [15, 'June', 2022]]

目標如下:

{2021:{'January':[11,12,13,14,15,16,17,18,19,....],'February':[1,2,3,4,5,6,7,8,9,....],'March':....},
 2022:{'January':[1,2,3,4,5,6,7,8,9,....],'February':[1,2,3,4,5,6,7,8,9,....],'March':....}
 }

我完全卡住了,無法弄清楚。 有人有想法嗎?

許多方法之一:

from collections import defaultdict
import json
dates = [[11, 'January', 2021],
 [12, 'January', 2021],
 [13, 'January', 2021],
 [13, 'June', 2022],
 [14, 'June', 2022],
 [15, 'June', 2022]]
 
out = defaultdict(lambda: defaultdict(list))
for date in dates:
    d, month, year = date
    out[year][month].append(d)
    
print (json.dumps(out))

Output:

{"2021": {"January": [11, 12, 13]}, "2022": {"June": [13, 14, 15]}}
    

這是使用字典理解和itertools.groupby的可能解決方案:

from itertools import groupby

{year: {month: list(zip(*v))[0] for month, v in groupby(x, lambda x: x[1])}
 for year, x in groupby(sorted(l, key=lambda x: (x[2], x[1])), key=lambda x: x[2])
}

output(我把一個1月份改成了2月份):

{2021: {'February': (13,), 'January': (11, 12)}, 2022: {'June': (13, 14, 15)}}
from collections import defaultdict ans = [ [11, 'January', 2021], [12, 'January', 2021], [13, 'January', 2021], [13, 'June', 2022], [14, 'June', 2022], [15, 'June', 2022] ] finalDict = defaultdict(lambda : defaultdict(list)) for day, month, year in ans: finalDict[year][month].append(day) print(finalDict)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM