【发布时间】:2020-05-15 14:29:18
【问题描述】:
我想编写一个代码来消除超过某个阈值的 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'}
【问题讨论】:
-
if type(v) is int and v > number:
标签: python dictionary iteration