I have a dictionary having its values as timestamp. Few keys have list of timestamps as values. I am trying to sum timestamps which is in value. But failing with below error:
Traceback (most recent call last):
File "testing.py", line 53, in <module>
for key, value in total_exam_items.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'
Below is my code:
total_items = {'item1': ['0:02:00'], 'item2': ['0:02:13'], 'item3': ['0:04:53'], 'item4': ['0:00:31', '0:05:17'], 'item5': ['0:04:31'], 'item6': ['0:04:34'], 'item6': ['0:13:26', '0:04:24']}
output = defaultdict(datetime)
for key, value in total_items.iteritems():
output[key] += value
Not sure where I am doing wrong? Any suggestions please???
I think the point here (besides .items()
) is that you need to use timedelta
if you want the sum of the times at each item, eg
from collections import defaultdict
from datetime import timedelta
from pandas import to_timedelta
total_items = {'item1': ['0:02:00'], 'item2': ['0:02:13'], 'item3': ['0:04:53'], 'item4': ['0:00:31', '0:05:17'], 'item5': ['0:04:31'], 'item6': ['0:04:34'], 'item6': ['0:13:26', '0:04:24']}
output = defaultdict(timedelta)
for key, value in total_items.items():
l = [to_timedelta(s) for s in value]
for t in l:
output[key] += t
# output
# defaultdict(datetime.timedelta,
# {'item1': Timedelta('0 days 00:02:00'),
# 'item2': Timedelta('0 days 00:02:13'),
# 'item3': Timedelta('0 days 00:04:53'),
# 'item4': Timedelta('0 days 00:05:48'),
# 'item5': Timedelta('0 days 00:04:31'),
# 'item6': Timedelta('0 days 00:17:50')})
Note that I'm using to_timedelta
from the pandas
lib because it offers convenient parsing of timedeltas from string.
If you are using Python3.x
instead of:
for key, value in total_items.iteritems():
Try:
for key, value in total_items.items():
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.