Reputation: 51
I want to round to the nearest 5 an element in the value of a dictionary.
Given a dictionary:
d = {'0': '0 43 1000 27 3 I', '1': '2 52 1020 28 3 J', '2': '2 11 10 281 32 T'}
I want to return the second element in the value of each dict, and round it to the nearest 5. So round 43 to 45, 52 to 50 and 11 to 10.
So far I only know how to return the value of a key in the dict,
for i in d['0']
but cant figure out the rest. Any help would be greatly appreciated.
Upvotes: 1
Views: 149
Reputation: 463
If you don't want to use the round
function in any case, the other way around by breaking the round
function itself is this:
def doit(d):
for key, value in d.items():
nums = value.split(" ")
if int(nums[1])%5>=3:
print((int(nums[1])//5)*5+5)
else:
print((int(nums[1])//5)*5)
Thanks.
Upvotes: 0
Reputation: 970
To round to nearest 5, you can use a custom function:
def round_five(x):
return 5 * round(x/5)
To access the second number in your string
of numbers:
for k, v in d.items():
# make a list out of the string
nums = v.split(" ")
# round the 2nd element
rounded = round_five(nums[1])
# do something with the second element:
print(rounded)
Upvotes: 3