通过从其他词典中提取数据来编译词典

2024-09-25 02:34:23 发布

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

我正在做一个项目,我从三个不同的数据集中提取数据,并将其结合起来查看竞选活动的贡献。为此,我将其中两个集合中的相关数据转换成字典(canDict和otherDict),ID号作为键,我需要的信息(党派关系)作为值。然后我编写了一个程序,根据密钥(我的第三套也包括这些身份证号码)提取聚会信息,并将它们与捐赠方的雇主和捐赠金额进行匹配。这是一个冗长的解释,但我认为这将有助于理解这段代码。你知道吗

我的问题是,由于某种原因,我的第三本字典(employerDict)无法编译。在这一步结束时,我应该有一个字典,其中包含雇主作为键,一个元组列表作为值,但是在运行它之后,字典仍然是空的。我已经一行接一行地讲了十几遍了,我都快发疯了——我一辈子都想不出为什么它不起作用,这让我很难找到答案。我评论了几乎每一行,试图让它更容易理解的上下文之外。有人能看出我的错误吗?

更新:我在最外层的for循环中添加了一个计数器n,以查看程序是否在迭代。你知道吗

更新2:我在创建变量party时添加了另一个if语句,以防数据[0]处的ID在canDict或otherDict中不存在。我还从评论中添加了一些已经建议的修复。你知道吗

n=0
with open(path3) as f:                         # path3 is a txt file
    for line in f:
        n+=1
        if n % 10000 == 0:
            print(n)
        data = line.split("|")                 # Splitting each line into its entries (delimited by the symbol |)
        party = canDict.get(data[0])           # data[0] is an ID number. canDict and otherDict contain these IDs as keys with party affiliations as values
        if party is None:
            party = otherDict[data[0]]         # If there is no matching ID number in canDict, search otherDict
            if party is None:
                party = 'Other'
        else:
            print('ERROR: party is None')
        x = (party, int(data[14]))             # Creating a tuple of the the party (found through the loop) and an integer amount from the file path3
        employer = data[11]                    # Index 11 in path3 is the employer of the person
        if employer != '':
            value = employerDict.get(employer) # If the employer field is not blank, see if this employer is already a key in employerDict
            if value is None:
                employerDict[employer] = [x]   # If the key does not exist, create it and add a list including the tuple x as its value
            else:
                employerDict[employer].append(x) # If it does exist, add the tuple x to the existing value
        else:
            print('ERROR: employer == ''')

Tags: the数据iniddataif字典is