首页 > 解决方案 > How to split a dict as per certain parts of the keys or extract values only for the keys have similar keywords

问题描述

I am pretty new in Python. I have a dict with values for some of the dates of different months. I want to split the dictionary as dates of each month or I want to get sum of the values for any or each days's of a month. I can get sum of the values for the whole dictionary but couldn't figure out how to get results as stated above. Here is my exiting dict:

Dict_Date_Vol = {'1/02/2021': 106239800, '2/02/2021': 83305400, '1/03/2021': 89880900, '3/03/2021': 84183100}

I want create a two new dict from here as like these two dictionaries: Dict_Feb = {'1/02/2021': 106239800, '2/02/2021': 83305400} and Dict_Mar = {'1/03/2021': 89880900, '3/03/2021': 84183100} or simply I want to get Values for Feb: and Values for Mar as two separate variables. Right now I can sum of all the values with the code below:

d = Dict_Date_Vol
def returnSum(d):
    sum =0
    for i in d:
        sum = sum + d[i]
    return sum
print('Total sum: ', returnSum(d))

I also can get a new dic for just a single key as below:

feb_vol = {k: v for k, v in d.items() if k in ('1/02/2021')}
print(feb_vol)
output: {'1/02/2021': 106239800}

However, I wanted to sort all of the keys based on the parts of keys (i.e. '02') so I can make a new dict for the month of Feb or with '03' for Mar. Any help would be highly appreciated. thanks in advance.

标签: pythondictionarysplit

解决方案


You can create a dictionary where you group the dates by month (I'm assuming you have only unique dates):

Dict_Date_Vol = {
    "1/02/2021": 106239800,
    "2/02/2021": 83305400,
    "1/03/2021": 89880900,
    "3/03/2021": 84183100,
}

months = {}
for k, v in Dict_Date_Vol.items():
    months.setdefault(k.split("/")[1], {})[k] = v

print(months)

Prints:

{'02': {'1/02/2021': 106239800, '2/02/2021': 83305400}, '03': {'1/03/2021': 89880900, '3/03/2021': 84183100}}

Then you can assign to your variables:

dict_feb = months.get("02")
dict_march = months.get("03")

print(dict_feb)
print(dict_march)

Prints:

{'1/02/2021': 106239800, '2/02/2021': 83305400}
{'1/03/2021': 89880900, '3/03/2021': 84183100}

推荐阅读