我收到了错误TypeError: 'int' object is not subscriptable
。
我想连接2个excel数据
所以我理想的输出是
1|1|Blear|40|false|l|America|A|1
2|5|Tom|23|true|o|UK|A|3
3|9|Rose|52|false|m
4|10|Karen||||Singapore|C|2
例如,user_id = 3的Rose数据不在第二个excel中,在这种情况下第二个数据为空即可。我在考虑将第二个excel在字典类型中添加到User模型。
我搜索了我认为此部分for data in data_dict
错误的错误,我将其更改为for data in range(len(data_dict))
但发生了同样的错误。我真的无法理解哪里出错了。我该如何解决这个问题?
现在views.py是
#coding:utf-8
from django.shortcuts import render
import xlrd
from .models import User
book = xlrd.open_workbook('../data/excel1.xlsx')
sheet = book.sheet_by_index(1)
def build_employee(employee):
if employee == 'leader':
return 'l'
if employee == 'manager':
return 'm'
if employee == 'others':
return 'o'
for row_index in range(sheet.nrows):
rows = sheet.row_values(row_index)
is_man = rows[4] != ""
emp = build_employee(rows[5])
user = User(user_id=rows[1], name_id=rows[2], name=rows[3],
age=rows[4],man=is_man,employee=emp)
user.save()
book2 = xlrd.open_workbook('../data/excel2.xlsx')
sheet2 = book2.sheet_by_index(0)
headers = sheet2.row_values(0)
large_item = None
data_dict = {}
for row_index in range(sheet2.nrows):
rows2 = sheet2.row_values(row_index)
large_item = rows2[1] or large_item
# Create dict with headers and row values
row_data = {}
for idx_col, value in enumerate(rows2):
header_value = headers[idx_col]
# Avoid to add empty column. A column in your example
if header_value:
row_data[headers[idx_col]] = value
# Add row_data to your data_dict with
data_dict[row_index] = row_data
for row_number, row_data in data_dict.items():
user1 = User.objects.filter(user_id = data['user_id']).exists()
if user1:
user1.__dict__.update(**data_dict)
user1.save()
现在Traceback是
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/XXX/testapp/app/views.py", line 123, in <module>
user1 = User.objects.filter(user_id = row_data['user_id']).exists()
KeyError: 'user_id'
答案 0 :(得分:2)
data
是一个整数。因此,像dict一样调用数据会引发这种期望。
>>> a=1
>>> a['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
为什么是int?因为您正在重复data
个键:
>>> a={1: 'x', 2: 'c'}
>>> for i in a: print(i)
...
1
2
尝试使用items()
:
>>> for key, value in a.items(): print(key, value)
...
1 x
2 c
或者,在您的具体案例中:
for row_number, row_data in data_dict.items():
print(row_number, row_data)
有关详细信息,请参阅looping techniques for dict documentation。