python附加字典实例

2024-04-20 02:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码块位于for循环中,而在这个代码块的上方是填充字典中的building、switch、max和total变量的信息。你知道吗

data1 = { building { switch_ip:
               { 'max': MAX,
                 'total': total
               }
             }
           }

当我运行代码时,输出是:

{'Azalea': {'10.16.62.10': {'max': '10', 'total': '43'}}}

有更多的数据,这个输出告诉我,for循环的每次迭代,字典都会被新的值填充。如果我在for循环中运行print语句,这就是输出:

{'Azalea': {'10.16.62.10': {'max': '10', 'total': '43'}}}
{'Azalea': {'10.16.62.12': {'max': '0', 'total': '43'}}}
{'Azalea': {'10.16.62.14': {'max': '1', 'total': '57'}}}
{'Azalea': {'10.16.62.15': {'max': '2', 'total': '33'}}}
{'Azalea': {'10.16.62.19': {'max': '0', 'total': '57'}}}
{'Azalea': {'10.16.62.20': {'max': '0', 'total': '57'}}}
{'Azalea': {'10.16.62.23': {'max': '1', 'total': '57'}}}
{'Azalea': {'10.16.62.24': {'max': '0', 'total': '57'}}}

这个输出是我希望在一个字典中包含的数据。我怎样才能把这本词典的每一个实例都附加到一本词典中呢?你知道吗


Tags: 数据代码ip信息for字典语句max
1条回答
网友
1楼 · 发布于 2024-04-20 02:15:02
for building in buildings:
    data1[building].update({ switch_ip:
                               { 'max': MAX,
                                 'total': total
                               }}

这将产生如下数据结构:

{'Azalea': { '10.16.62.10': { 'max': '10', 'total': '40' }},
           { '10.16.62.12': { 'max': '12', 'total': '32' }}}

相关问题 更多 >