【问题标题】:Can not update a dictionary无法更新字典
【发布时间】:2022-08-06 20:28:51
【问题描述】:

我正在编写一个 python 程序来扫描给定目录的 .csv 文件。我想要每个单词出现的数量作为我的输出。这是我现在编码的。

import os
import pandas as pd

root = D:\\dir1\\dir2\\data
ext = \'.csv\'


dict_napak_file = {} #creating two dictionaries to later try to write data into
dict_napak_dir = {}

for datoteka in os.scandir(root): #going thorugh files in the given directory
    if datoteka.path.endswith(ext): #only do below code if the file ends with .csv
        df = pd.read_csv(datoteka, encoding = \'cp1252\')
        fifth_column = df.iloc[:, 4]  # Gets all rows for the fifth column (index starts at 0)
        counts = fifth_column.value_counts()
        dict_napak_file.update(counts)  #this is where the problem starts. It does write in the dictionary. But only for one file
    dict_napak_dir = dict_napak_dir.update(dict_napak_file) #Now I want to merge all dictionaries made while scanning the files into one dictionary to use for further data anayisis

print(\"done\")

我收到此错误:

--------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [50], in <cell line: 4>()
      8         counts = forth_column.value_counts()
      9         dict_napak_dat.update(counts)
---> 10     dict_napak_dir = dict_napak_dir.update(dict_napak_dat)
     12 print(\"done\")

AttributeError: \'NoneType\' object has no attribute \'update\'
  • dict_napak_dir.update 返回None。而不是dict_napak_dir = dict_napak_dir.update(dict_napak_dat),仅将其更改为dict_napak_dir.update(dict_napak_dat)。当您重新分配时,您将 None 分配给变量,并且在下一次迭代中它会引发您看到的错误。

标签: python pandas dictionary


【解决方案1】:

a.update(b) 是一个函数不是返回任何东西,即它返回None。它直接将字典b 添加到字典a 中。如果我们将输出存储在变量中,例如c = a.update(b),打印出c 将返回None。但是,如果您打印a,它应该在控制台中打印合并的字典。这是演示代码:

a = {'something': 'something2'}
b = {'something3': 'something4'}
c = a.update(b)
print(a)
print(c)

这是控制台:

{'something': 'something2', 'something3': 'something4'}
None

【讨论】:

    猜你喜欢
    • 2021-08-20
    • 2015-09-08
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2022-11-08
    • 2013-02-23
    • 2019-05-20
    • 2019-05-04
    相关资源
    最近更新 更多