我想要一本字典有user_id的密钥&数据

时间:2017-09-09 05:56:35

标签: python django excel

我想让一本字典有user_id的密钥& data.In 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()

files = glob.glob('./user/*.xlsx')

for x in files:
    if "$" not in x:
      book3 = xlrd.open_workbook(x)
      sheet3 = book3.sheet_by_index(0)
      cells = [
    ]
      data_dict = OrderedDict()
      for key, rowy, colx in cells:
         try:
            data_dict[key] = sheet3.cell_value(rowy, colx)
         except IndexError:
            data_dict[key] = None

      data_dict_key ={}
      data_dict_key['user_id'].update(data_dict_key)

但是当我运行此代码时,会发生错误

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/XXX/testapp/app/views.py", line 164, in <module>
    data_dict_key['user_id'].update(data_dict_key)
KeyError: 'user_id'

我真的不明白为什么会发生这种错误。 当我打印出data_dict时,它是

OrderedDict([('user_id', '1'), ('name', 'Blear'), ('nationality', 'America'), ('domitory', 'A'), ('group', 1)])

我的理想词典是

dicts = {
    1: {
        user_id: 1,
        name_id: 'Blear',
        nationality: 'America',
        domitory: 'A',
        group: 1,
    },
    2: {
    },
}

我该如何解决这个问题?我应该使用声明吗?

我通过查看评论重写了我的代码,现在views.py是

data_dict_key ={}
for x in files:
    if "$" not in x:
      book3 = xlrd.open_workbook(x)
      sheet3 = book3.sheet_by_index(0)
      cells = [
    ]
      data_dict = OrderedDict()
      for key, rowy, colx in cells:
         try:
            data_dict[key] = sheet3.cell_value(rowy, colx)
         except IndexError:
            data_dict[key] = None

            if data_dict['user_id'] in data_dict_key:
               data_dict_key[data_dict['user_id']].update(data_dict)
               continue
            data_dict[data_dict_key['user_id']] = data_dict

1 个答案:

答案 0 :(得分:0)

你的循环应该是这个。希望这会有所帮助。

data_dict_key ={}
for x in files:
    if "$" not in x:
      book3 = xlrd.open_workbook(x)
      sheet3 = book3.sheet_by_index(0)
      cells = [
    ]
      data_dict = OrderedDict()
      for key, rowy, colx in cells:
         try:
            data_dict[key] = sheet3.cell_value(rowy, colx)
         except IndexError:
            data_dict[key] = None

      if data_dict['user_id'] in data_dict_key:
         data_dict_key[data_dict['user_id']].update(data_dict)
            continue
      data_dict_key[data_dict['user_id']] = data_dict