Reputation: 11
My goal is:
def DogYears():
small_dog = {
1 : 15,
2 : 24,
3 : 28,
4 : 32,
5 : 36
6 : 40
.
.
.
}
My question is how could I automate this process so that I don't have to fill it manually?
I was thinking of something like this, at least in that direction, of course it doesn't work:
def DogYears():
small_dog = {
range(15, 80, 4)
}
I somehow also need to assign key & value pair. Any ideas?
Upvotes: 1
Views: 315
Reputation: 12990
Ok, based off of Eduardo's answer, I think I have an equation. You don't need a dictionary:
def small_dog_years(age):
if age <= 1: return 15
return min(24 + (age - 2) * 4, 80)
print(small_dog_years(1)) # 15
print(small_dog_years(2)) # 24
print(small_dog_years(3)) # 28
print(small_dog_years(4)) # 32
print(small_dog_years(8)) # 48
print(small_dog_years(15)) # 76
You could then generate your dictionary (if you still wanted to) with a dict comprehension:
small_dog = {i: small_dog_years(i) for i in range(1, 17)}
print(small_dog)
>>> {1: 15, 2: 24, 3: 28, 4: 32, 5: 36, 6: 40, 7: 44, 8: 48, 9: 52, 10: 56, 11: 60, 12: 64, 13: 68, 14: 72, 15: 76, 16: 80}
Upvotes: 0
Reputation: 4606
You could use a dictionary constructor with the ranges that include the human years and dog years, you would have to add in the outlier 15
, which would come at the end, if you need the dictionary properly sorted you could then just sort it as well using lambda
. Also you need to extend your ranges by 1 unit since they are not inclusive.
small_dog = dict(zip(range(2, 17), range(24, 84, 4)))
small_dog[1] = 15
small_dog = dict(sorted(small_dog.items(), key=lambda x: x[0]))
# {1: 15, 2: 24, 3: 28, 4: 32, 5: 36, 6: 40, 7: 44, 8: 48, 9: 52, 10: 56, 11: 60, 12: 64, 13: 68, 14: 72, 15: 76, 16: 80}
Upvotes: 0
Reputation: 1714
Using a list allows you to have the ages keep a normal order and access the values by their index. Since all your keys only increase by one, then using a list would be a more appropriate data structure. You can just store your range()
result into a list variable. Then to access the correct year, you can get the age like I did in the GetAge
function passing in the year and list.
def DogYears():
small_dog = range(15, 80, 4)
def GetAge(year, dog_list):
index = year - 1
if index >= 0 and index < len(dog_list):
return dog_list[index]
Upvotes: 1
Reputation: 1000
If you want to build a dictionary, a simple for
is enough.
def DogYears():
small_dog = {}
small_dog[1] = 15
i = 2
for j in range(24, 80, 4):
small_dog[i] = j
i = i + 1
Upvotes: 1