字典上的"int"对象没有属性"items"错误


# 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'

我真的不明白为什么会出现在这里,它是一个字典,但程序说它是整数看来我犯了一个棘手的错误,所以如果你能帮我找出我做错了,我会很高兴的。

似乎你想输出year_count{"2010": 4, "2011": 5}?错误是因为year_count不是int

可以使用list

# 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))

或者你可以使用dictionary

# 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)

相关内容

  • 没有找到相关文章

最新更新