what is the format for creating a dictionary that stores time values (minutes and seconds)? for example I want to create a dictionary the holds a runners sprint time: mySprints = {"first":4:30,"second":3:13,"third":5:36}
and so on. In what format is the time entered in the dictionary?
Thank you in advance.
Asked
Active
Viewed 668 times
0

as134_user3693277
- 135
- 6
-
Does [this](https://stackoverflow.com/questions/6580168/what-type-to-store-time-length-in-python) answer your question? – Enzo Feb 15 '21 at 11:52
-
An array/list is probably a more appropriate data structure because the elements have an inherent order – byxor Feb 15 '21 at 11:58
1 Answers
1
I'm sure there are many methods, but one option would be to input the time as a string:
your_dict = {"first": "4:30","second": "3:13"}
Or you could use the time class within the datetime module:
example = datetime.time(0,4,30) # this would be 0 hours, 4 minutes and 30 seconds
your_dict = {"first": datetime.time(0,4,30),"second": datetime.time(0,3,13)} # etc...
You could also then create a lambda function to initiate the time a bit easier so you wouldn't have to write datetime.time(0, minutes, seconds) in the dictionary each time, for example:
time_obj = lambda m, s: datetime.time(0,m,s)
your_dict['third'] = time_obj(5, 36)
print(your_dict['third']) # this would return: 00:05:36
To answer your question in the comment, you can add timedelta objects together, for example:
x = datetime.timedelta(minutes=2, seconds=20) # notice the .timedelta this time
y = datetime.timedelta(minutes=1, seconds=10)
print(x+y) # returns: 0:03:30
To sort, you can sort a list of timedelta objects using python sorted() function, for example:
x = datetime.timedelta(minutes=2, seconds=20)
y = datetime.timedelta(minutes=1, seconds=10)
z = datetime.timedelta(minutes=0, seconds=50)
times = [x, y, z]
print(times)
# returns: [datetime.timedelta(0, 140), datetime.timedelta(0, 70), datetime.timedelta(0, 50)]
print(sorted(times))
# returns: [datetime.timedelta(0, 50), datetime.timedelta(0, 70), datetime.timedelta(0, 140)]
To sort it within a dictionary, I would suggest having a look at this stackoverflow question.

Chad Goldsworthy
- 69
- 1
- 7
-
How are the string time values converted to time? I want to add up all the values to get a total time. and is it possible to sort the time values from lease to greatest? – as134_user3693277 Feb 15 '21 at 12:13
-
In that case, don't use strings, rather use timedelta. I have added an answer to your questions above. – Chad Goldsworthy Feb 15 '21 at 12:26