检查字典中的非零值

Checking for non-zero values in a dictionary

我正在编写一个连接到 Cisco 交换机或路由器的程序,然后检查 'show int ' 的输出。我然后 process/parse 数据到我有一个二十一的字典 key/value 对。所有值都是整数。它完全按照我的意愿工作 到此为止。

我在想象下一步要做什么时遇到了一些困难,我希望能得到一些想法 and/or 指导。

我想做的是:

检查每个值。如果所有值都为零,则跳过该字典。 如果任何单个值非零(如果不是,它将是一个正整数 零),那么我想将整个字典保存到一个文件中。

我的程序的每次迭代都会创建一个表示来自交换机或路由器端口的数据的字典。

因为我想要整个字典(所有 21 个 key/value 对)即使单个值不为零,我不确定是否添加所有值然后 检查总和是否 > 0 是最佳选择。

我可能会检查数千个交换机端口。

在我看来,'best' 将开始检查值,一旦我遇到非零值,我就想保存整个字典并继续下一个(循环遍历例如,交换机上的端口),但我不确定如何实现。

如果能提供有关如何最好地完成此任务的一些想法或示例,我将不胜感激。

哦,我对使用这个词犹豫不决'best'。因为我将处理数千个端口,所以我不想要一种低效的方法,这就是为什么 我在犹豫要不要简单地把所有的值加起来。

我只是不确定如何输入代码:“只要我看到一个非零 值,保存整个字典并继续下一个。

如果所有非零键都具有相同的值,你可以只做dict.get(x),如果x不在字典中,它会return none。

否则:

    for value in dict.values():
      if value != 0:
        return true
    return false

如果所有值都不为零,您可能还想先执行 dict.get(0)。

这是对请求的直接翻译,从您已经完成的部分开始,并结合了字典的 any() function applied to the values

# I am in the process of writing a program that connects to a Cisco switch or
# router and then examines the output of a 'show int '. I then process\parse the
# data to the point where I have a dictionary of twenty-one key\value pairs.
# All values are integers.
for device in devices:
    s = run_show_interfaces(device)
    d = preprocess_parse(s)

    # Check each value. If ALL values are zero, then skip that dictionary. If ANY
    # single value is non-zero (it will be a positive integer if it is not zero),
    # then I want to save to a file the entire dictionary.
    if any(d.values()):
        filename = os.path.join(device, '.txt')
        with open(filename, 'w') as f:
            json.dump(d, f)

仅供参考,any() 函数有一个提前输出,一旦找到非零值就会停止查找。在 Python 3 中,values() returns 数据视图,因此它不会复制所有信息。在Python2中,使用viewvalues()也可以达到同样的效果。综合起来,这会给你带来很好的表现。