user1831571
user1831571

Reputation: 13

Modifying a dictionary with datetime as keys

For example:

{datetime.date(2000, 1, 15): [1],
 datetime.date(2000, 1, 14): [5],
 datetime.date(2000, 1, 3): [4],
 datetime.date(2005, 1, 10): [2],
 datetime.date(2005, 1, 16): [4],
 datetime.date(2005, 1, 5): [2]}

to just:

{(2000, 1): [10], (2005,1): [8]}

basically omitting the day, and adding the values. I can't seem to figure out how to remove datetime.date.

Upvotes: 1

Views: 3606

Answers (2)

Eric
Eric

Reputation: 97575

"one-line"r:

newdict = {
    (key.year, key.month): sum(
        v[0] for k, v in olddict.iteritems()
        if (key.year, key.month) == (k.year, k.month)
    )
    for key in olddict
}
>>> newdict
{(2000, 1): 10, (2005, 1): 8}

This might be a little less efficient than 0605002's answer.


Or a more conventional solution:

from collections import defaultdict

newdict = defaultdict(lambda: [0])
for key in olddict:
    newdict[(key.year, key.month)][0] += olddict[key][0]

Upvotes: 3

Sufian Latif
Sufian Latif

Reputation: 13356

Simple:

for key in olddict:
    if (key.year, key.month) in newdict:
        newdict[(key.year, key.month)][0] += olddict[key][0]
    else:
        newdict[(key.year, key.month)] = [olddict[key][0]]

Learn more about datetime objects from python docs.

Upvotes: 0

Related Questions