0

I know to this question sounds weird but I'll try to explain it as well as I can. I have dict with a date as key and int as a value. It looks like this:

{'22-07-2018,': 1,
 '14-07-2018,': 1,  
 '12-07-2018,': 1,
 '4-03-2018,':  1,
 '20-02-2018,': 1,
 '15-02-2018,': 2,  
 '25-11-2017,': 1,
 '11-11-2017,': 2,
 '26-10-2017,': 2,
 '21-10-2017,': 6,}

Now I need to add items to this dict with 0 as between all these dates so like this:

{'22-07-2018,': 1,
 '21-07-2018,': 0,
 '20-07-2018,': 0,
 '19-07-2018,': 0,
 '18-07-2018,': 0,
  ...
 '14-07-2018,': 1,
 '13-07-2018,': 0,
 '12-07-2018,': 0,
 '11-07-2018,': 0,
 '10-07-2018,': 0,
 ...  
 '4-03-2018,':  1,
 ...}

It's really important for me to have this dict in order.

Does anyone know how to do this?

xaos_xv
  • 759
  • 1
  • 10
  • 27
  • "It's really important for me to have this dict sorted." By sorted you mean in order? – Denziloe Aug 27 '18 at 16:44
  • Yes. I need it. – xaos_xv Aug 27 '18 at 16:46
  • 6
    Either use `OrderedDict` or Python 3.6+ All other versions of Python dicts are not ordered. – dawg Aug 27 '18 at 16:47
  • 1
    A `dict` is not the right structure for this then, because it's not ordered. If you just want results I recommend you use DataFrames from `pandas` which is a library designed for this kind of task. – Denziloe Aug 27 '18 at 16:48
  • 3
    I'm not sure what you are asking either. As explained, dictionaries are not ordered; just add additional keys with whatever value you need, it's not as if you can insert between two keys *anyway*. – Martijn Pieters Aug 27 '18 at 16:50
  • Now I formatted this `dict` properly – xaos_xv Aug 27 '18 at 17:00

1 Answers1

3

Perhaps using Pandas to do something like this (assuming the commas where erroneous in the keys to the dictionary)?

It is not clear from your sample expected results why there are only certain dates with a filled value of zero.

d = {'22-07-2018': 1, 
     '14-07-2018': 1, 
     '12-07-2018': 1, 
     '4-03-2018': 1, 
     '20-02-2018': 1, 
     '15-02-2018': 2, 
     '19-12-2017': 1, 
     '25-11-2017': 1, 
     '11-11-2017': 2, 
     '26-10-2017': 2, 
     '21-10-2017': 6}

s = pd.Series(d)
s.index = pd.to_datetime(s.index)
s = s.reindex(pd.DatetimeIndex(start=s.index.min(), end=s.index.max(), freq='D')).fillna(0)

>>> s
2017-10-21    6
2017-10-22    0
2017-10-23    0
2017-10-24    0
2017-10-25    0
2017-10-26    2
...
2018-12-06    0
2018-12-07    1
Freq: D, dtype: float64
Alexander
  • 105,104
  • 32
  • 201
  • 196