[英]Adding items in a dictionary but the precious value seems to be overwritten via for loop in Python
[英]Adding elements to a dictionary via for loop
Python 3.6
所有調試輸出均來自PyCharm 2017.1.2
我有一個正在解決一個缺陷的程序。
這是我遇到的問題:
def striplist(errlist):
return [item.strip() for item in errlist]
for line in shintlist:
errors_list = striplist(line.split(","))
errRegex = re.compile(r'(\d+)(\s)(\D+)')
errdict = {}
for elem in errors_list:
mo = errRegex.search(elem)
errdict[mo.group(3)] = int(mo.group(1))
if int(mo.group(1)) > 0:
print("There are errors")
else:
print("There are no errors")
print(errdict)
**注意**打印語句目前僅供我使用,以檢查程序邏輯。 它們將在以后刪除。
在執行這些指令時,“ shintlist”是逗號分隔的字符串列表。
__len__ = {int} 9
0 = {str} ' 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored'
1 = {str} ' 0 watchdog'
2 = {str} ' 0 input packets with dribble condition detected'
3 = {str} ' 5912 packets output, 738736 bytes, 0 underruns'
4 = {str} ' 0 output errors, 0 collisions, 2 interface resets'
5 = {str} ' 4 unknown protocol drops'
6 = {str} ' 0 babbles, 0 late collision, 0 deferred'
7 = {str} ' 0 lost carrier, 0 no carrier'
8 = {str} ' 0 output buffer failures, 0 output buffers swapped out'
上面的代碼有效。 它正確地在','上分割,然后去除空白。 然后,它在errdict {}中創建一個字典key:value條目:
errdict = {dict} {'input errors': 0}
__len__ = {int} 1
'input errors' (64451912) = {int} 0
我遇到的問題是:每次迭代時,errdict {}被'shintlist'的下一行覆蓋。
我想做的是:
如果每個單個項目的每個單個值為零(0):如果int(mo.group(1))> 0:則跳過此接口。 如果任何一個值都大於零,那么我希望字典'errdict {}'包含上述'shintlist'中的所有行,因此我只有一個字典包含所有內容。
**注2 **這些條目:5912數據包輸出,738736字節,對於活動接口將始終為非零。 稍后再處理。
處理“ shintlist”中的每一行時,以下每一行都是errdict {}的狀態:
{'input errors': 0, 'CRC': 0, 'frame': 0, 'overrun': 0, 'ignored': 0}
{'watchdog': 0}
{'input packets with dribble condition detected': 0}
{'packets output': 6304, 'bytes': 786190, 'underruns': 0}
{'output errors': 0, 'collisions': 0, 'interface resets': 2}
{'unknown protocol drops': 4}
{'babbles': 0, 'late collision': 0, 'deferred': 0}
{'lost carrier': 0, 'no carrier': 0}
{'output buffer failures': 0, 'output buffers swapped out': 0}
如果任何單個值都不為零,我想要一個包含所有行和值的單個字典,這樣我就可以打印出顯示所有有錯誤接口的報告。
除非我離開,否則我會問如何將每行追加到errdict {}而不是覆蓋?
謝謝。
問題出在示例代碼的第9行中-您在for line...
循環的每次迭代中都將errdict
重新初始化為空字典。 您想在該循環的頂部(而不是在示例代碼的第3行)對其進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.