‘int’ 对象在字典上没有属性 ‘items’ 错误
python 220
原文标题 :‘int’ object has no attribute ‘items’ error on dictionary
# Create the CSV file: csvfile
csvfile = open('crime_sampler.csv', 'r')
# Create a dictionary that defaults to a list: crimes_by_district
crimes_by_district = defaultdict(list)
# Loop over a DictReader of the CSV file
for row in csv.DictReader(csvfile):
# Pop the district from each row: district
district = row.pop('District')
# Append the rest of the data to the list for proper district in crimes_by_district
crimes_by_district[district].append(row)
# Loop over the crimes_by_district using expansion as district and crimes
for district, crimes in crimes_by_district.items():
# Print the district
print(district)
# Create an empty Counter object: year_count
year_count = Counter()
# Loop over the crimes:
for crime in crimes:
# If there was an arrest
if crime['Arrest'] == 'true':
# Convert the Date to a datetime and get the year
year = datetime.strptime(crime['Date'], '%m/%d/%Y %I:%M:%S %p').year
# Increment the Counter for the year
year_count += 1
# Print the counter
print(year_count)
我收到一个错误:
AttributeError Traceback (most recent call last)
/tmp/ipykernel_608/212322553.py in <cell line: 2>()
14 year = datetime.strptime(crime['Date'], '%m/%d/%Y %I:%M:%S %p').year
15 # Increment the Counter for the year
---> 16 year_count += 1
17
18 # Print the counter
/usr/lib/python3.8/collections/__init__.py in __iadd__(self, other)
814
815 '''
--> 816 for elem, count in other.items():
817 self[elem] += count
818 return self._keep_positive()
AttributeError: 'int' object has no attribute 'items'
我真的不明白为什么会在这里发生,这是一个字典,但程序说它是整数似乎我犯了一个棘手的错误,所以如果你帮我找出我做错了,我会很高兴
回复
我来回复-
WSUN000 评论
好像要输出
year_count
之类的{"2010": 4, "2011": 5}
?错误是因为year_count
不是int
你可以使用一个列表
# Create an empty list object: year_count year_count = [] # Loop over the crimes: for crime in crimes: # If there was an arrest if crime['Arrest'] == 'true': # Convert the Date to a datetime and get the year year = datetime.strptime(crime['Date'], '%m/%d/%Y %I:%M:%S %p').year # Increment the list for the year year_count.append(year) # Print the counter print(Counter(year_count))
或者你可以使用字典
# Create an empty list object: year_count year_count = dict() # Loop over the crimes: for crime in crimes: # If there was an arrest if crime['Arrest'] == 'true': # Convert the Date to a datetime and get the year year = datetime.strptime(crime['Date'], '%m/%d/%Y %I:%M:%S %p').year # Increment the dict for the year year_count[year] = year_count.get(year, 1) + 1 # Print the counter print(year_count)
2年前