Creating dictionary of items from Excel with mutliple keys

648 views
Skip to first unread message

Atri Mahapatra

unread,
Aug 13, 2016, 12:44:22 PM8/13/16
to openpyxl-users
I am trying to create a following dictionary. I am reading data from excel which has data in the following format:

Sl no:  Name Thickness Length Material Width Quantity Side
,,         ..           ..              ..             ..          ..          ..           ..

It has 20 rows of data.


The dictionary, I would like to make is

Data_Dict = [
{ 'Name': 'X', 'Length': '10' , 'Width': '5', 'Quantity': 2 'Area': 50};
{ 'Name': 'Y', 'Length': '20' , 'Width': 10', 'Quantity': 1 'Area': 200};
.
.
.
.
till 20 rows
];

I would like to add another key 'Area' as shown above. I used the following code(s):

using openpyxl:
d={}
for i  in range(3,sheet.max_row+1):
    #for j in range(3,9):
        #for k in range(0,5):
          Name = sheet.cell(row= i,column=3).value
          Length =sheet.cell(row =i,column=6).value
          Breadth= sheet.cell(row=i,column=7).value
          Quantity = sheet.cell (row=i,column=8).value
          Area = sheet.cell(row =i,column=6).value*sheet.cell(row=i,column=7).value
          d[Name]= Length,Breadth,Quantity,Area

which gave an output like:
['X': (10, 5, 2, 50), 'Y': (20, 10, 1, 2232600), 'Z': (5, 2, 1, 10), .............]

The main purpose is to sort the dictionary based on different criteria like Length or Area. I think the first one may be easier to sort. However if there are any better way to represent  the dictionary  and the code so that it can be sorted later based on different attributes please feel free to suggest.

Thanks,
Atri

Thomas Nygårds

unread,
Aug 15, 2016, 2:42:21 AM8/15/16
to openpyxl-users
This could maybe do it for you?


list_to_be_sorted
=[]
for i in range(3, sheet.max_row + 1):
    d
= {}

   
Name = sheet.cell(row=i, column=3).value
   
Length = sheet.cell(row=i, column=6).value
   
Breadth = sheet.cell(row=i, column=7).value
   
Quantity = sheet.cell(row=i, column=8).value
   
Area = sheet.cell(row=i, column=6).value * sheet.cell(row=i, column=7).
value
    list_to_be_sorted
.append({'Length': Length, 'Breadth': Breadth, 'Quantity': Quantity, 'Area': Area})


from operator import itemgetter
sorted_list = sorted(list_to_be_sorted, key=itemgetter('Area'))
#or
sorted_list = sorted(list_to_be_sorted, key=itemgetter('Area'), reverse=True)


Regards
Thomas
Reply all
Reply to author
Forward
0 new messages