0

i have a dictionary like :

  dictt =  {"2020-01-02": 34 , "2019-02-19": 43 , "2012-08-19": 52 , "2010-10-10": 10 } 

I want to filter this dictionary based on key (date) and keeping only the date greater or equal "2012-01-01" , please help

Expected output :

  dictt =  {"2020-01-02": 34 , "2019-02-19": 43 , "2012-08-19": 52} 
Hamza usman ghani
  • 2,264
  • 5
  • 19
Arvea
  • 11
  • 1
  • 1
    Does this answer your question? [Filter dict to contain only certain keys?](https://stackoverflow.com/questions/3420122/filter-dict-to-contain-only-certain-keys) – David May 19 '21 at 08:17

2 Answers2

0

Try:

dictt =  {"2020-01-02": 34 , "2019-02-19": 43 , "2012-08-19": 52 , "2010-10-10": 10 } 
dictt = {k: v for k, v in dictt.items() if k > "2012-01-01"}
print(dictt)
>> {'2020-01-02': 34, '2019-02-19': 43, '2012-08-19': 52}
Hamza usman ghani
  • 2,264
  • 5
  • 19
0

If you want to do the comparison with datetime objects:

from datetime import datetime as dt

my_dict = {"2020-01-02": 34 , "2019-02-19": 43 , "2012-08-19": 52 , "2010-10-10": 10 }
cust_date_dict = {d: n for d, n in my_dict.items() if dt.strptime(d, '%Y-%m-%d') >= dt.strptime("2012-01-01", '%Y-%m-%d')}

Output of print(cust_date_dict):

{'2020-01-02': 34, '2019-02-19': 43, '2012-08-19': 52}

flooo
  • 26
  • 5