Home > Software engineering >  create nested dict from nested list python
create nested dict from nested list python

Time:10-02

I'm trying to convert a list of lists into a nested dict. The nested list looks like this (list of lists containing dates):

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

the goal is the following:

{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':....}
 }

i'm totally stuck and not able to figure it out. Does anyone have an idea?

CodePudding user response:

One of the many approaches:

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]}}
    

CodePudding user response:

Here is a possible solution using a dictionary comprehension and 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 (I changed one January to February) :

{2021: {'February': (13,), 'January': (11, 12)}, 2022: {'June': (13, 14, 15)}}

CodePudding user response:

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)


  • Related