在Python中累积字典值的总计
嘿,我需要一点帮助。我正试图用Python编写一个程序,从我的case元素[10]、元素[11]和元素[15]中的csv文件中获取某些元素,并输出一个漂亮的字典。我要做的是将元素[11]和[15]中的数字相加,并将其用于字典的值部分,并将元素[10]作为键。我遇到的问题是,每次找到密钥时,我都希望将元素[11]和[15]添加到以前的总数中。例如,键阿拉斯加被发现53次,总数应为1198047。我知道如果我的陈述是错误的,我就是不知道怎么说。这是我到目前为止的代码在Python中累积字典值的总计,python,Python,嘿,我需要一点帮助。我正试图用Python编写一个程序,从我的case元素[10]、元素[11]和元素[15]中的csv文件中获取某些元素,并输出一个漂亮的字典。我要做的是将元素[11]和[15]中的数字相加,并将其用于字典的值部分,并将元素[10]作为键。我遇到的问题是,每次找到密钥时,我都希望将元素[11]和[15]添加到以前的总数中。例如,键阿拉斯加被发现53次,总数应为1198047。我知道如果我的陈述是错误的,我就是不知道怎么说。这是我到目前为止的代码 def main():
def main():
inreport = open("state_crime - CS152.csv", "r")
report = inreport.readlines()
statedict = {}
total = 0
for lines in report[1:]:
values = lines.split(',')
totalcrime = int(values[11]) + int(values[15])
state = values[10]
statedict[state] = totalcrime
if state in statedict:
statedict[state] = total + totalcrime
for akey in statedict.keys():
print (akey," "*(20-len(akey)), (f"{statedict[akey]:,}").rjust(10))
inreport.close()
main()
浏览csv文件中的几行,看看代码会做些什么,这将对您有所帮助 在本例中,“total”不是一个有用的变量,因为它始终保持为0 此外,“statedict[state]=totalcrime”这一行也无济于事。假设在第二排,阿拉斯加的总犯罪率为500。然后statedict['Alaska']将被设置为500。那么,假设第5排也是阿拉斯加的,犯罪总数为300。此行将去掉前面的值,并将statedict['Alaska']设置为300 您可以尝试替换此部分
statedict[state] = totalcrime
if state in statedict:
statedict[state] = total + totalcrime
以下是:
if state in statedict:
statedict[state] = statedict[state] + totalcrime #if the state is already in the keys, adds totalcrime to the existing value
else:
statedict[state] = totalcrime #if the state isn't already in the dictionary, creates a new key for it with totalcrime as the value
浏览csv文件中的几行,看看代码会做些什么,这将对您有所帮助 在本例中,“total”不是一个有用的变量,因为它始终保持为0 此外,“statedict[state]=totalcrime”这一行也无济于事。假设在第二排,阿拉斯加的总犯罪率为500。然后statedict['Alaska']将被设置为500。那么,假设第5排也是阿拉斯加的,犯罪总数为300。此行将去掉前面的值,并将statedict['Alaska']设置为300 您可以尝试替换此部分
statedict[state] = totalcrime
if state in statedict:
statedict[state] = total + totalcrime
以下是:
if state in statedict:
statedict[state] = statedict[state] + totalcrime #if the state is already in the keys, adds totalcrime to the existing value
else:
statedict[state] = totalcrime #if the state isn't already in the dictionary, creates a new key for it with totalcrime as the value
您有一个名为“total”的变量,它始终为0。你应该把它扔掉。 由于您通过
statedict[state]=total+totalcrime
以下是一个解决方案:
totalcrime = int(values[11]) + int(values[15])
state = values[10]
if state in statedict:
statedict[state] += totalcrime
else:
statedict[state] = totalcrime
目标是告诉python添加statedict dict中已经存在的值,或者如果不存在,则使用first total crime值创建状态键。您有一个名为“total”的变量,它始终为0。你应该把它扔掉。 由于您通过
statedict[state]=total+totalcrime
以下是一个解决方案:
totalcrime = int(values[11]) + int(values[15])
state = values[10]
if state in statedict:
statedict[state] += totalcrime
else:
statedict[state] = totalcrime
目标是告诉python,如果它已经在statedict dict中,则添加该值;如果不在statedict dict中,则只创建具有第一个总犯罪值的状态键。请共享csv的一部分和预期输出。预期输出为1198047请共享csv和预期输出的一部分。预计产量为1198047。非常感谢!没问题。仅供参考,除非您通过单击答案旁边的复选标记接受答案,否则此问题将继续显示为未回答。非常感谢!没问题。仅供参考,除非您通过单击答案旁边的复选标记接受答案,否则此问题将继续显示为未回答。非常感谢!非常感谢你!