You can greatly simply your code by considering just three cases.
You first simply check if the key
is in the obj
, returning an empty list if not.
Then, you check the type, and if its anything but a list
, you return an empty list.
Finally, use a list comprehension to extract the 10
s in the list and return them.
def get_elements_that_equal_10_at_a_value(obj, key):
if key not in obj:
return []
value = obj[key]
if type(value) != list:
return []
return [val for val in value if val == 10]
obj1 = {'key': [1000, 10, 50, 10]}
output1 = get_elements_that_equal_10_at_a_value(obj1, 'key')
print(output1) # --> [10, 10]
obj2 = {'key': 10}
output2 = get_elements_that_equal_10_at_a_value(obj2, 'key')
print(output2) # --> []
Edit: You could simplify this even further by making use of dict.get()
, setting obj[key]
to be the empty list if the key
does not exist. Thanks to @m-z for suggesting this.
def get_elements_that_equal_10_at_a_value(obj, key):
value = obj.get(key, [])
if type(value) != list:
return []
return [val for val in value if val == 10]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…