I need to make a function that returns a dictionary where values are doubled if values from previous dictionary are bigger than 10
def dbl(d1):
d = {x: d1.get(x, 0) * 2 for x in set(d1)}
return d
This is my code that doubles. I can't figure out where to put if > 10
My try:
a = {"a": 1, "b": 17, "c": 15}
def dbl(d1):
d = {x: d1.get(x, 0) * 2 for x in set(d1) if x > 10}
return d
TypeError: '>' not supported between instances of 'str' and 'int'
CodePudding user response:
Any item in set(d1)
gives you one of dictionary keys ("a", "b", "c"), not dictionary values. Try to put if d1[x] > 10
instead of if x > 10
CodePudding user response:
Using dict comprehension you can do is as follows :
def dbl(d1):
d = {k:v*2 if v>10 else v for (k,v) in d1.items()}
return d
This solution permits to keep the value that are < 10 and double the ones that are > 10.