简体   繁体   中英

Sort a dictionary of arrays in python with a tuple as the key

I a dictionary with a string tuple as the key and an array as the value:

some_dict = {}
some_dict[(A,A)] = [1234, 123]
some_dict[(A,B)] = [1235, 13]
some_dict[(A,C)] = [12, 12]
some_dict[(B,B)] = [12621, 1]
...

I am writing this to a csv file:

for k,v in some_dict.iteritems():
    outf.write(k[0]+","+k[1]+","+str(v[0])+","str(v[1])+"\n")

output:

A,A,1234,123
A,B,1235,13
A,C,12,12
B,B,12621,1

I'd like to sort it based on the first number "column" before writing to a file (or after and just rewrite?) so the output should be like:

B,B,12621,1
A,B,1235,13
A,A,1234,123
A,C,12,12
     ^ 
     Sorted on this 'column'

How do I do this? The file is very large, so doing it before writing would be better I think.

Sort your dictionary items; the sorted() function takes a key function to determine what to sort on; for the (key, value) tuple, use a lambda:

sorted_data = sorted(some_dict.iteritems(), key=lambda i: i[1][0], reverse=True)
for (k1, k2), (v1, v2) in sorted_data:

I used reverse=True to have bigger values first.

Try to avoid reinventing the wheel, there is an excellent csv module available to you:

import csv

with open(filename, 'wb') as f:
    writer = csv.writer(f)
    for (k1, k2), (v1, v2) in sorted(some_dict.iteritems(), key=lambda i: i[1][0]):
        writer.writerow([k1, k2, v1, v2])

and you won't have to explicitly convert the integers to strings either.

Make use of the sorted() function builtin and specify a key by which to sort:

for k,v in sorted(some_dict.iteritems(), key=lambda t: t[1][0]):
    print k,v

#output:
(A, C) [12, 12]
(A, A) [1234, 123]
(A, B) [1235, 13]
(B, B) [12621, 1]

To order from large to small, simply set the reverse keyword argument:

for k,v in sorted(some_dict.iteritems(), key=lambda t: t[1][0], reverse=True):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM