0

I want to parse excel and put data in the model(User).Now I want to make a dictionary which has excel data. Excel is excel1 I wrote in views.py

#coding:utf-8
from django.shortcuts import render
import xlrd
def try_to_int(arg):
    try:
        return int(arg)
    except:
        return arg

def main():
    book3 = xlrd.open_workbook('./data/excel1.xlsx')
    sheet3 = book3.sheet_by_index(0)

    data_dict = {}
    tag_list = sheet3.row_values(0)[1:]
    for row_index in range(1, sheet3.nrows):
        row = sheet3.row_values(row_index)[1:]
        row = list(map(try_to_int, row))
        data_dict[row_index] = dict(zip(tag_list, row))

    print(data_dict)

main()

and it printed out {1: {'A': '', 'area': 'New York', 'C': 0, 'name': 'Blear', 'B': ''}, 2: {'A': '', 'area': 'Chicago', 'C': '', 'name': '', 'B': 0}, 3: {'A': 0, 'area': 'London', 'C': '', 'name': '', 'B': ''}, 4: {'A': '', 'area': 'Singapore', 'C': '', 'name': 'Tom', 'B': ''}, 5: {'A': 0, 'area': 'Delhi', 'C': '', 'name': '', 'B': ''}, 6: {'A': '', 'area': 'Beijing', 'C': 1, 'name': '', 'B': ''}} But

I cannot understand why output dictionary is mess.I want to get a dictionary like

{1: {'name': 'Blear', 'area': 'New York', 'A': '', 'B': '', 'C': 0}, 
 1: {'name': 'Blear', 'area': 'Chicago', 'A': '', 'B': 0, 'C': ''}, 
 1: {'name': 'Blear', 'area': 'London', 'A': 50, 'B': 0, 'C': ''}, 
 2: {'name': 'Tom', 'area': 'Singapore', 'A': '', 'B': '', 'C': ''}}・・・

What is wrong in my code? How should I fix this?

DYZ
  • 55,249
  • 10
  • 64
  • 93
user8563636
  • 163
  • 1
  • 5
  • 12
  • I believe this post has the answer [why dictionary values aren't in the inserted order](https://stackoverflow.com/questions/6061380/why-dictionary-values-arent-in-the-inserted-order) – Andrew Halpern Sep 08 '17 at 03:01
  • 2
    how can your desired result have key `1` multiple times? – nos Sep 08 '17 at 03:07
  • Possible duplicate of [Why dictionary values aren't in the inserted order?](https://stackoverflow.com/questions/6061380/why-dictionary-values-arent-in-the-inserted-order) – DYZ Sep 08 '17 at 03:10

0 Answers0