'Python - If > 16 and for in dictionary list comprehension
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'
Solution 1:[1]
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
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David |
| Solution 2 | Maxime Lavaud |
