简体   繁体   English

使用元组作为键对python中的数组字典进行排序

[英]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: 我正在将此写入csv文件:

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: 我想在写入文件之前(或之后再重写?)基于第一个数字“ column”对它进行排序,因此输出应为:

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; sorted()函数采用一个key函数来确定要排序的内容; for the (key, value) tuple, use a lambda: 对于(key, value)元组,请使用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. 我使用reverse=True首先具有更大的值。

Try to avoid reinventing the wheel, there is an excellent csv module available to you: 尝试避免重新发明轮子,这里有一个出色的csv模块可供您使用:

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: 利用内置的sorted()函数并指定用于排序的键:

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: 要从大到小排序,只需设置reverse关键字参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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