【问题标题】:Python KeyError: 'C'Python KeyError:'C'
【发布时间】:2021-04-24 17:36:15
【问题描述】:

我正在尝试编写对数表。输出应该是三行表示城市总数、唯一人口计数和第一位频率分布,然后是三列表示数字、计数和百分比。

这是我当前的代码:

    
def main():       
    
    population=set()
    #declaring dictionary to hold the count of #each digit
    digits={}
    #initializing totCities to 0 that holds the count of total number of cities
    totCities=0
    #initializing all digits in the dictionary to 0
    for i in range(1, 10):
        num=str(i)
        num=num[0]
        digits[num]=0
#opening Census_2009.txt file
    try:
        infile=open("Census_2009.txt",'r')
#throwing error if file cannot be opened and exiting the program
    except OSError:
        print("Could not open file")
        exit()
#ignoring the headernext(infile)
  #iterating through each line in file
    for i in infile:
#incrementing totCities for each city
        totCities+=1
        line=i.rstrip().split('\t')
#adding each population count to the set and incrementing the count of the first digit in #the dictionary
        population.add(line[-1])
        digits[line[-1][0]]+=1
#closing Census_2009.txt
    fileinfile.close()
#opening benford.txt file to write the Output
    outfile=open("benford.txt",'w')
    print("Output written to benford.txt")
#writing the output to the file
    outfile.write("Total number of cities: {}\n".format(totCities))
    outfile.write("Unique population counts: {}\n".format(len(population)))
    outfile.write("Digit\tCount\tPercentage\n")
    for key, value in digits.items():
        outfile.write("{}\t{}\t{}\n".format(key, value, round(((value/totCities)*100), 1)))
#closing benford.txt
    fileoutfile.close()
    
    
main()

但是,我收到此错误:

  File "<ipython-input-15-061b69b87f23>", line 28, in main
    digits[line[-1][0]]+=1

KeyError: 'C'

你知道这个错误具体是为了什么,以及如何修复它吗? 抱歉,代码太长了。

【问题讨论】:

  • 需要一个文件样本以便重现
  • 欢迎来到 Stack Overflow!请阅读How to debug small programs。您还可以使用Python-Tutor,它有助于逐步可视化代码的执行。
  • line 是一个字符串列表。所以line[-1] 是一个字符串,line[-1][0] 只是一个字符,即'C'。由于数字仅包含1-9,因此当被要求输入digits['C']时会给出KeyError

标签: python keyerror


【解决方案1】:

正如其他人指出的那样,print(line[-1][0]) 可能提供了您没有想到的东西,即'C' 而不是数字。我们看不到您的输入数据,因此很难知道这是数据不一致的问题,还是您选择了错误的字段。

如果您确信您的代码选择了正确的字段,但这是您愿意忽略的偶尔行数据,您可以使用类似的方法对该部分进行快速的部分防弹操作

pop_field = line[-1]
if pop_field.is_numeric():
    population.add(pop_field)    
lead_char = pop_field[0]
if lead_char.isnumeric():
    digits[lead_char]+=1

其他一些不请自来的提示,接受或留下:

  • 您可能只使用整数 1-9 作为字典键,而不是转换为字符串。
  • 可以使用快捷方式来初始化字典,比如

digits = dict((d, 0) for d in range(1, 10))

# digits will be {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}

  • 对于计数任务,collections 模块具有处理大多数用例的 Counter 类。

祝你好运!

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 2022-01-21
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多