在Python字典中获取类似值的总和

时间:2012-05-15 13:08:47

标签: python collections dictionary

抱歉,我又回来了。这次我试图获得每个停车场的登记数量,并添加了以下代码:

data_dict = {}
dict_list = []
def createNameDict(filename):
  path = "C:\Users\user\Desktop"
  basename = "ParkingData_Part2.txt"
  filename = path + "//" + basename
  file = open(filename)
  contents = file.read()
  print contents,"\n"


  data_list = [lines.split(",") for lines in contents.split("\n")]



  for line in data_list:
    regNumber = line[0]
    name = line[1]
    phoneExtn = line[2]
    carpark = line[3]
    details = (name,phoneExtn,carpark)

    data_dict[regNumber] = details
  print data_dict,"\n"
  print data_dict.items(),"\n"

def getDetails(regNumber):
  try:
    print data_dict[regNumber]
  except:
    print regNumber, " not in dictionary"
    return
def addRegistration(regNumber, details):
  if regNumber not in data_dict:
    data_dict[regNumber] = details

    print regNumber, ":", details, "Registration details added"
  else:
    print regNumber, "Key Already exist, \n"


  return data_dict
def registrationsPerCarpark(carpark):

  for regNumber, details in data_dict:        
    return [key for key, value in data_dict.iteritems() if value == details][0]
  #for carpark in data_dict.values():
   # print sum(int(carpark))
    #return

但是值并没有加起来,因为它们不是数字。我在谷歌搜索了很多但是无法获得有关此信息的任何信息。我的代码输出是这样的:

====== Loading Progam =======
>>> createNameDict("C:\Users\user\Desktop//ParkingData_Part2.txt")
EDF768, Bill Meyer, 2456, Vet_Parking
TY5678, Jane Miller, 8987, AgHort_Parking
GEF123, Jill Black, 3456, Creche_Parking
ABC234, Fred Greenside, 2345, AgHort_Parking
GH7682, Clara Hill, 7689, AgHort_Parking
JU9807, Jacky Blair, 7867, Vet_Parking
KLOI98, Martha Miller, 4563, Vet_Parking
ADF645, Cloe Freckle, 6789, Vet_Parking
DF7800, Jacko Frizzle, 4532, Creche_Parking
WER546, Olga Grey, 9898, Creche_Parking
HUY768, Wilbur Matty, 8912, Creche_Parking 

{'HUY768': (' Wilbur Matty', ' 8912', ' Creche_Parking'), 'GH7682': (' Clara Hill', ' 7689', ' AgHort_Parking'), 'GEF123': (' Jill Black', ' 3456', ' Creche_Parking'), 'WER546': (' Olga Grey', ' 9898', ' Creche_Parking'), 'TY5678': (' Jane Miller', ' 8987', ' AgHort_Parking'), 'ABC234': (' Fred Greenside', ' 2345', ' AgHort_Parking'), 'KLOI98': (' Martha Miller', ' 4563', ' Vet_Parking'), 'EDF768': (' Bill Meyer', ' 2456', ' Vet_Parking'), 'JU9807': (' Jacky Blair', ' 7867', ' Vet_Parking'), 'DF7800': (' Jacko Frizzle', ' 4532', ' Creche_Parking'), 'ADF645': (' Cloe Freckle', ' 6789', ' Vet_Parking')} 

[('HUY768', (' Wilbur Matty', ' 8912', ' Creche_Parking')), ('GH7682', (' Clara Hill', ' 7689', ' AgHort_Parking')), ('GEF123', (' Jill Black', ' 3456', ' Creche_Parking')), ('WER546', (' Olga Grey', ' 9898', ' Creche_Parking')), ('TY5678', (' Jane Miller', ' 8987', ' AgHort_Parking')), ('ABC234', (' Fred Greenside', ' 2345', ' AgHort_Parking')), ('KLOI98', (' Martha Miller', ' 4563', ' Vet_Parking')), ('EDF768', (' Bill Meyer', ' 2456', ' Vet_Parking')), ('JU9807', (' Jacky Blair', ' 7867', ' Vet_Parking')), ('DF7800', (' Jacko Frizzle', ' 4532', ' Creche_Parking')), ('ADF645', (' Cloe Freckle', ' 6789', ' Vet_Parking'))] 

>>> registrationsPerCarpark("AgHort_Parking")
The error was:__getitem__
Attribute not found.
You are trying to access a part of the object that doesn't exist.
Please check line 48 of C:\Users\user\Desktop\159171\assignment2_part2

3 个答案:

答案 0 :(得分:0)

for regNumber, details in data_dict是错误的,你不能以这种方式迭代dict。您可能意味着for regNumber, details in data_dict.items()(或iteritems(),但这将是Python 2特定的。)

如果我理解正确的任务,函数体看起来应该如下:

def registrationsPerCarpark(carpark):

    return sum(value[2]=carpark for value in data_dict.values())

请注意您的值中的空格:例如,您应该寻找' AgHort_Parking',而不是'AgHort_Parking'。要解决此问题,请更改createNameDict以执行

carpark = line[3].strip()

等等。 此外,createNameDict内存效率低,因为它会立即将文件内容加载到内存中。要减少内存使用量,请执行以下操作:

data_list = []
with open(filename) as infile:
  data_list = [lines.split(",") for lines in contents.split("\n")]
  for line in infile:
        data_list.append(line.split(','))
        print line

答案 1 :(得分:0)

def registrationsPerCarpark(carpark):
    for regNumber, details in data_dict:        
        return [key for key, value in data_dict.iteritems() if value == details][0]

您的for循环不起作用,因为迭代的in dictionary构造只返回key,而不是(key, value)对。其次,你从不使用carpark变量。第三,它是无关紧要的,因为你后来在你的return语句中循环它,虽然你使用它是没有意义的。你可以假设你只需要计算特定停车场的车数吗?

答案 2 :(得分:0)

这是另一种更紧凑的方法。

import csv
from collections import defaultdict

rows = defaultdict(set)

with open('in.csv') as f:
  lines = csv.reader(f)
  for line in lines:
      rows[line[3].strip()].add((line[0],line[1],line[2]))

for key in rows:
   print 'Total number of cars for %s is %s' % (key,len(rows[key]))

结果是:

The total number of cars for Creche_Parking is 4
The total number of cars for AgHort_Parking is 3
The total number of cars for Vet_Parking is 4