N
N
novicheck2016-07-28 13:28:32
Python
novicheck, 2016-07-28 13:28:32

How to write sorted data to csv file?

According to the assignment, I have to build a table in csv format from the database in Mongo and I did it this way

f = open('grafinfopay.txt', 'w')
heh = list(db.events.aggregate(
[
    {"$match": {"$and":[{"status": 'start'}, {"is_buyer": 1}]}},
    {"$group": {"_id": "$eventName", "players": {"$addToSet": "$uid"}}},
    {"$unwind": "$players"},
    {"$group": {"_id": "$_id", "Count": {"$sum": 1}}}
]))
znacheniya = list()
fu = {}
a = [0]*400 
output_file = open("donators.csv", "wb")
wrtr = csv.writer(output_file)
for i in heh:
    lol = i.values()
    value = lol.pop(0)
    key = lol.pop(0)
    fu = {key : value}
    num = re.findall(r'\d+', str(fu))
    poz = int(num.pop(0))
    if poz < 1000:
        a[poz - 1] = fu
        wrtr.writerow([key, value])
f.close()
output_file.close()

But the csv file comes out unsorted, but unfortunately I need to get a sorted file. And I can't figure out how to sort it.
Here is an example of data (this is "a" and it is already sorted, but they can be mixed up):
a = [{u'Level 1': 46404}, {u'Level 2': 45606}, {u'Level 3': 45335}]

PS
This code performs another function, so some lines may not be relevant to the question.
Update:
Here is an example input
heh = [{u'Count': 361, u'_id': u'Level 302'}, {u'Count': 315, u'_id': u'Level 299'}, {u'Count': 353, u'_id': u'Level 311'}]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-07-28
@novicheck

pythoncentral.io/how-to-sort-python-dictionaries-b...
stackoverflow.com/questions/72899/how-do-i-sort-a-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question