Python-从给定字典中过滤负值

作为数据分析的一部分,我们将遇到各种场景,以从字典中删除负值。为此,我们必须遍历字典中的每个元素,并使用条件检查值。下面的两种方法可以实现。

使用for循环

W简单地使用for循环遍历列表的元素。在每次迭代中,我们使用items函数将元素的值与0进行比较,以检查负值。

示例

dict_1 = {'x':10, 'y':20, 'z':-30, 'p':-0.5, 'q':50}

print ("Given Dictionary :", str(dict_1))

final_res_1 = dict((i, j) for i, j in dict_1.items() if j >= 0)

print("After filtering the negative values from dictionary : ", str(final_res_1))

输出结果

运行上面的代码将为我们提供以下结果:

Given Dictionary : {'x': 10, 'y': 20, 'z': -30, 'p': -0.5, 'q': 50}

After filtering the negative values from dictionary : {'x': 10, 'y': 20, 'q': 50}

使用lambda函数

我们将lambda函数用于更短,更清晰的语法。在这种情况下,我们实现与上述相同的逻辑,但改用lambda函数。

示例

dictA = {'x':-4/2, 'y':15, 'z':-7.5, 'p':-9, 'q':17.2}

print ("\nGiven Dictionary :", dictA)

final_res = dict(filter(lambda k: k[1] >= 0.0, dictA.items()))

print("After filtering the negative values from dictionary : ", str(final_res))

输出结果

运行上面的代码将为我们提供以下结果:

Given Dictionary : {'x': -2.0, 'y': 15, 'z': -7.5, 'p': -9, 'q': 17.2}

After filtering the negative values from dictionary : {'y': 15, 'q': 17.2}

以上是 Python-从给定字典中过滤负值 的全部内容, 来源链接: utcz.com/z/335352.html

回到顶部