Home > Mobile >  Multiply python dictionary keys by a constant
Multiply python dictionary keys by a constant

Time:11-18

I need to define a function def times_ten(start: int, end:int) that will multiply each key by 10 and return a dictionary with those values. Example: d = times_ten(3,6) print(d) returns {3: 30, 4: 40, 5: 50, 6: 60}.

CodePudding user response:

Try this:

def times_ten(start, end):
    return {n: n * 10 for n in range(start, end)} 

CodePudding user response:

You could use a dict comprehension

def times_ten(start, stop):
    return {i: i*10 for i in range(start, stop)

>>> times_ten(3, 6)
{3: 30, 4: 40, 5: 50}

Note that is is canonical for most ranges in python to be half-open, in other words the include the start value but exclude the end value, [start, stop).

  • Related