【发布时间】:2014-06-24 07:28:01
【问题描述】:
我有一个以数组为元素的字典。 说:
masterListShort = {'a': [5, 2, 1, 2], 'b': [7, 2, 4, 1], 'c': [2, 0, 1, 1]}
我想按值的第一个元素对该字典进行反向排序。 然后我想将我的输出写入一个制表符分隔的文件,如下所示:
<key> <value1> <value2> <value3> etc.
我将字典写入文件的当前代码如下所示:
# write the masterListShort to file
outFile2 = open('../masterListShort.tsv', 'w')
for item in sorted(masterListShort):
tempStr = '\t'.join(map(str, masterListShort[item]))
outFile2.write(str(item) + '\t' + tempStr + '\n')
outFile2.close()
此代码工作正常,只是不对列表进行排序。 我希望我的输出以制表符分隔的文件格式编写。 所以:
b 7 2 4 1
c 5 2 1 2
a 2 0 1 1
到目前为止,我已经找到了以下命令,并且想知道是否可以将它们应用到我的代码中:
import operator
sorted(myDict, key=operator.itemgetter(1))
【问题讨论】:
-
请测试您的样品;您的示例字典使用了完全不正确的语法。
-
对不起,我只是从头开始写的。
标签: python list sorting python-2.7 dictionary