我想编写一个在忽略字符串的同时消除超过某个阈值的int值的代码。目前,我所拥有的代码抛出错误'>' not supported between instances of 'str' and 'int'。这是代码:

dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 'montana' }
number = 2

def remove_numbers_larger_than(number, dictionary):
    for k, v in list(dictionary.items()):
        if v > number:
            del dictionary[k]
return dictionary



print(remove_numbers_larger_than(number, dictionary))


输出应为:{'a': 1, 'b': 2, 'e': 'montana'}

最佳答案

这可以帮助您:

dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 'montana' }
number = 2

newd = {k:v for k,v in dictionary.items() if type(v) != int or v <= number}
print(newd)
# {'a': 1, 'b': 2, 'e': 'montana'}

10-08 05:37
查看更多