doubts
doubts

Reputation: 157

How can i get this output in order?

import xlrd
import sys

from collections import defaultdict
out = defaultdict(list)

workbook = xlrd.open_workbook('Dummy Input Data.xlsx')
worksheet = workbook.sheet_by_index(0)
headers = worksheet.row(0)
result = []
for index in range(worksheet.nrows)[1:]:
    result.append(worksheet.row(index)[0].value)
for uniq in set(result):
    sum = 0
    for index in range(worksheet.nrows)[1:]:
       if uniq == worksheet.row(index)[0].value:
            sum = sum + worksheet.row(index)[4].value
    out[uniq] = int(sum)
for rec in out:
    print rec+" "+str(out[rec])

I got output like this:
Engineer-2 16
Engineer-3 19
Engineer-1 11
Engineer-4 24
Engineer-5 12

how to sort the names and numbers, I need result in orderly like:

Engineer-1 11

Engineer-2 16

Engineer-3 19

Engineer-4 24

Engineer-5 12

how to get result as like above,it should take starting from 1,2,3,4,5... but i am getting output not in order.

Upvotes: 0

Views: 73

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90929

You are use two different data-structures that do not have any sense of order - dictionary as well as set - so getting the result in an order different from original order (in which it existed in the excel) should not be suprising.

If what you want is to order the result using the name from 1-5 , then you can use sorted() on out.keys() , Example -

for rec in sorted(out.keys()):
    print rec+" "+str(out[rec])

If your real intention is to get the data back in original format , it existed in the excel , then you should not create a set for uniq elements, instead create result as a list of unique elements by using another set to store already seen elements. Example -

seen = set()
result = []
for index in range(worksheet.nrows)[1:]:
    e = worksheet.row(index)[0].value
    if e not in seen:
        seen.add(e)
        result.append(e)

Then use that, result list to iterate the dictionary to print the values. Example -

for rec in result:
    print rec+" "+str(out[rec])

Upvotes: 0

luoluo
luoluo

Reputation: 5533

try this:

for rec in sorted(out.keys()):
    print rec+" "+str(out[rec])

DEMO:

>>> a
{'Engineer-2': 16, 'Engineer-3': 19, 'Engineer-1': 11, 'Engineer-4': 24, 'Engineer-5': 12}
>>> for k in sorted(a.keys()):
...     print k, a[k]
... 
Engineer-1 11
Engineer-2 16
Engineer-3 19
Engineer-4 24
Engineer-5 12

Upvotes: 1

Related Questions