簡體   English   中英

將鍵和值添加到字典

[英]Add key and value to dictionary

我試圖將新的鍵/值對添加到(空)字典中。 我有一個帶有字符串(年)的文本文件,腳本應該計算年份的出現。

    with open ("results/results_%s.txt" % bla, "r") as myfile:
       for line in myfile:
        line = line.translate(None, ''.join(chars_to_remove))
        abc = line.split("_", 2)
        year = abc[1:2]
        year = ''.join(year)
        year = year.translate(None, ''.join(chars_to_remove))
        raey = {}
        #increment the value of the "year"-key, if not present set it to 0 to avoid key erros
        raey[year] = raey.get(year, 0) + 1

但是,如果返回例如{'2004':1},但它應該建立一個字典(如{1993:2,2012:3}),如果我在for循環中插入“ print”語句,則得到例:

{'1985': 1}
{'2062': 1}
{'1993': 1}
{'2000': 1}
{'2007': 1}
{'2009': 1}
{'1993': 1}
{'1998': 1}
{'1993': 1}
{'1998': 1}
{'2000': 1}
{'2013': 1}
{'1935': 1}
{'1999': 1}
{'1998': 1}
{'1992': 1}
{'1999': 1}
{'1818': 1}
{'2059': 1}
{'1990': 1}

它沒有建立正確的字典,代碼正在用每個循環替換字典。 我究竟做錯了什么?

問題是您正在for循環中初始化dict,因此每次都會創建一個新字典。 相反,將其移出

with open ("results/results_%s.txt" % bla, "r") as myfile:
  raey = {}
  for line in myfile:
    line = line.translate(None, ''.join(chars_to_remove))
    abc = line.split("_", 2)
    year = abc[1:2]
    year = ''.join(year)
    year = year.translate(None, ''.join(chars_to_remove))
    #increment the value of the "year"-key, if not present set it to 0 to avoid key erros
    raey[year] = raey.get(year, 0) + 1

每次調用raey = {}將清除字典。 將那條線移動到循環之前以初始化字典一次,並將其填充到循環中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM