python - 检查字典中的非零值

标签 python dictionary python-3.6

我正在编写一个程序,该程序连接到 Cisco 交换机或路由器,然后检查“show int”的输出。然后我处理/解析数据,直到我有一个包含二十一个的字典 键/值对。所有值都是整数。它完全按照我想要的方式工作 到目前为止。

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

我想做的是:

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

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

由于我想要整个字典(所有二十一个键/值对),即使单个值非零,我不确定是否添加所有值,然后 检查总和是否 > 0 是最好的选择。

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

在我看来,“最好”是开始检查值,一旦我达到非零值,我就想保存整个字典并继续下一个(循环通过交换机上的端口) ,例如),但我只是不确定如何实现这一点。

我希望获得一些有关如何最好地完成此任务的想法或示例。

哦,我对使用“最好”这个词犹豫不决。由于我将处理数千个端口,所以我不想要一种低效的方法,这就是为什么 我犹豫是否简单地将所有值相加。

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

最佳答案

这是请求的直接翻译,从您已经完成的部分开始,并合并 any()函数应用于 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() 返回数据 View ,因此它不会复制所有信息。在 Python 2 中,使用 viewvalues()以达到同样的效果。总而言之,这将为您带来出色的表现。

关于python - 检查字典中的非零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43826775/

相关文章:

python - 如何在没有黑色背景的情况下将 png 图像作为 Sprite 上传到 pygame 中?

Python3.6 : Error importing gi module

python - 在需要非贪婪匹配的情况下匹配正则表达式

python - 使用 Python 检查 Adwords 帐户中是否已存在标签?

python - 从包含 IP 地址的 Pandas df 中删除行

python - 在元组中添加元素

javascript - 使用对象作为 ES2015 映射键

c# - 使用 LINQ 将 Dictionary<Guid,IList<String>> 转换为 Dictionary<string,IList<Guid>>?

xml - 有没有办法快速访问 OWL (RDF/XML) 文件中的所有注释和子注释?

python - 尝试使用经度和纬度获取距离,但一直运行到错误 : 'Series' object has no attribute 'radians'