Reputation: 11
I am trying to format the durationdictionary
to get (hours:mins:seconds) for each unique element. There are 7 unique numbers in the the dictionary.
Below is a sample of the durationdictionary
: Can someone please show me how to do this. (Format is {Phonenumber : Total seconds}
)
{'7807890123': 129370, '7803214567': 179532, '7808907654': 121726, '7809876543': 190211}
Here's my code:
def call_list():
list =[line.strip().split(";") for line in calls_file]
#Gets the total amount of seconds for each unique user in the list.
for i in list:
duration = int(i[3])
if i[1] in durationdictionary.keys():
durationdictionary[i[1]] += duration
else:
durationdictionary[i[1]] = duration
# Gets the total amount of seconds from each individual in the dictionary called durationdictionary at index 1 and converts in into the format (h:m:s)
for i in list:
min_t = math.floor(durationdictionary[i[1]]//60)
second = math.floor(durationdictionary[i[1]]//60)
minute = min_t//60
hour = minute//60
durationdictionary[i[1]] = str(hour) + "h" + str(minute) + "m" + str(second) + "s"
print(durationdictionary)
Upvotes: 0
Views: 83
Reputation: 104712
To break up your number of seconds into hours, minutes and seconds, I suggest using divmod
repeatedly. Calling divmod(a, b)
returns a 2-tuple, (a//b, a%b)
(and it may be more efficient at calculating them than using both operators yourself):
minutes, seconds = divmod(durationdictionary[i[1]], 60)
hours, minutes = divmod(minutes, 60)
I think there's another issue though, since you're iterating over list
to get i
, but modifying durationdictionary
in a way that can't be repeated (you're converting the values from integers to strings. You probably want to be iterating over the dictionary's items()
, or maybe just building a new dictionary instead of modifying the values of the existing one.
Here's some code that updates durrationdictionary
in place, using the above logic to convert the times:
for phone_number, seconds in durationdictionary.items():
minutes, seconds = divmod(seconds, 60)
hours, seconds = divmod(minutes, 60)
durationdictionary[phone_number] = "{}h{}m{}s".format(hours, minutes, seconds)
Upvotes: 1