python - 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.
解决方案
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}
推荐阅读
- python - 如何将输入的字符串的每个字符加1并输出加密的字符串?
- python - Python,如何使嵌套循环适用于多列 csv 文件?
- pine-script - 更新值或创建新系列
- node.js - Node.js express 无法在 Heroku 上设置 cookie
- laravel - Laravel Echo 没有收到更多事件
- python - CSV 文件处理 - 我的程序不会输出任何内容
- python - 计算器中的问题
- python - 打开浏览器时在 Selenium 中打开 Tor 时出错
- python - 我收到 LocalUnboundError
- ruby-on-rails - 使用 Rails 6 `insert_all` 从 CSV 文件导入模型,这会引发 NoMethodError