我正在做一个项目,我从三个不同的数据集中提取数据并将其组合起来查看广告系列的贡献。为此,我将两个集合中的相关数据转换为字典(canDict和otherDict),其中ID号作为键,我需要的信息(派对从属关系)作为值。然后我写了一个程序来根据密钥提取党的信息(我的第三组也包括这些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 == ''')
答案 0 :(得分:0)
感谢大家的所有输入 - 但是,它看起来像我的数据文件的问题,而不是程序的问题。 Dangit。