Creating a nested dictionary using for loop

Question:

I have a bigger code from which I obtain some datetime object for some events (YYYY-MM-DD) for two years (2021,2022) out of which I want to group data together in a nested dictionary structure. For a particular event, I want the following structure –

event_name:
   {2021:
      {01:
         number_of_datetime_having_month january,
       02:
         number_of_datetime_having_month_feb
       ...etc etc upto december},
    2022:
      {01:
         number_of_datetime_having_month_january,
       ........etc etc upto december}
    }

I am planning to write this data to csv and plot this afterwards.
I am wondering what will be the best approach. Hard-coding the schema beforehand?

Asked By: mrin9san

||

Answers:

from datetime import datetime, timedelta
datetimes = [datetime.now() + timedelta(days=20*i) for i in range(20)]

# Sparse result (zero-counts excluded):

result = {}
for dt in datetimes:
    months_data = result.setdefault(dt.year, {})
    months_data[dt.month] = months_data.setdefault(dt.month, 0) + 1

# Non-sparse result:

result = {}
for y in set(o.year for o in datetimes):
    result[y] = {}
    for m in range(1,13):
        result[y][m] = 0
        
for dt in datetimes:
    result[dt.year][dt.month] += 1

# Output result
from pprint import pprint
pprint(result)

Sparse output:

{2022: {9: 1, 10: 2, 11: 1, 12: 2},
 2023: {1: 1, 2: 2, 3: 1, 4: 2, 5: 1, 6: 2, 7: 1, 8: 2, 9: 2}}

Non-sparse output:

{2022: {1: 0,
        2: 0,
        3: 0,
        4: 0,
        5: 0,
        6: 0,
        7: 0,
        8: 0,
        9: 1,
        10: 2,
        11: 1,
        12: 2},
 2023: {1: 1,
        2: 2,
        3: 1,
        4: 2,
        5: 1,
        6: 2,
        7: 1,
        8: 2,
        9: 2,
        10: 0,
        11: 0,
        12: 0}}
Answered By: kwiknik

I made some changes in the earlier answer of kwiknik (the sparse one), however i have to admit his approach is more elegant. Neverthless, I am posting my approach too.

from datetime import datetime, timedelta
datetimes = [datetime.now() + timedelta(days=20*i) for i in range(20)]
result = {}
for dt in datetimes:
    months_data = result.setdefault(dt.year, {})
    months_data[dt.month] = months_data.setdefault(dt.month, 0) + 1 
############################################################################       
count=0
for year in result.keys():
    for k in range(1,13,1):
        for items in result[year].keys():
            if items==k:
                pass
            else:
                count=count+1 
        if count==len(result[year].keys()):
            result[year][k]='0'
        count=0  
        kk= dict(sorted(result[year].items()))
        result[year]=kk
print(result)

Output

{2022: {1: '0', 2: '0', 3: '0', 4: '0', 5: '0', 6: '0', 7: '0', 8: '0', 9: 1, 10: 2, 11: 1, 12: 2}, 2023: {1: 1, 2: 2, 3: 1, 4: 2, 5: 1, 6: 2, 7: 1, 8: 2, 9: 1, 10: 1, 11: '0', 12: '0'}}
Answered By: mrin9san
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.