koogee
koogee

Reputation: 963

python remove keys whose values add up to a total

dict1 = {datetime.timedelta(3, 21388, 702926): 2, datetime.timedelta(10, 21388, 702926): 1, datetime.timedelta(3, 65011, 297074): 2, datetime.timedelta(14, 65011, 297074): 1, datetime.timedelta(17, 65011, 297074): 1, datetime.timedelta(0, 65011, 297074): 1, datetime.timedelta(7, 65011, 297074): 1, datetime.timedelta(10, 65011, 297074): 1, datetime.timedelta(0, 21388, 702926): 1}

I am trying to remove the timedeltas, the sum of whose values equals 6. They also have to be the largest timedeltas in the dict.

Here's how I'm trying to solve it:

x = 0
for key in dict1:
    if key in sorted(dict1)[-1] and x < 6:
        x = x+dict1[key]
        del dict1[key]

My thinking is sorted(dict) returns a list of timedeltas with the largest ones at the end. I could match each key with the largest timedelta in the list, sum its value to x & remove that key until the x reaches 6. But this returns:

TypeError: argument of type 'datetime.timedelta' is not iterable

Stumped again.

Upvotes: 0

Views: 84

Answers (1)

tk.
tk.

Reputation: 626

From the comments I deduce that you want to delete the biggest timedeltas until the aggregated sum of their values reaches 6.

values_sum = 0
for key in sorted(dict1,reverse=True):
    values_sum +=dict1[key]
    del dict1[key]
    if values_sum >= 6:
        break    

Upvotes: 1

Related Questions