【发布时间】:2014-01-30 05:55:55
【问题描述】:
我正在尝试按列表对字典进行排序。列表列表中的项目是字典中的键。我之前问过,但答案并没有解决问题。
我的输入列表是:
mylist= [
['why', 'was', 'cinderella', 'late', 'for', 'the', 'ball', 'she', 'forgot', 'to', 'swing', 'the', 'bat'],
['why', 'is', 'the', 'little', 'duck', 'always', 'so', 'sad', 'because', 'he', 'always', 'sees', 'a', 'bill', 'in', 'front', 'of', 'his', 'face'],
['what', 'has', 'four', 'legs', 'and', 'goes', 'booo', 'a', 'cow', 'with', 'a', 'cold'],
['what', 'is', 'a', 'caterpillar', 'afraid', 'of', 'a', 'dogerpillar'],
['what', 'did', 'the', 'crop', 'say', 'to', 'the', 'farmer', 'why', 'are', 'you', 'always', 'picking', 'on', 'me']
]
我的字典有点像这样:
myDict = {'to': [7, 11, 17, 23, 24, 25, 26, 33, 34, 37, 39, 41, 47, 48, 53, 56],
'jam': [20], 'black': [5], 'farmer': [11],
'woodchuck': [54], 'has': [14, 16, 51], 'who': [16]
}
我的代码是:
def sort_by_increasing_order(mylist, myDict):
#temp = sorted(myDict, key=myDict.get)
temp = sorted(myDict, key=lambda tempKey: for tempKey in mylist, reverse=True )
return temp
类似:
sort_by_increasing_order(['d', 'e', 'f'], {'d': [0, 1], 'e': [1, 2, 3], 'f': [4]})
result: ['f', 'e', 'd']
所以对于我的示例输入,它看起来像:
sort_by_increasing_order(mylist, myDict)
>> ['to','woodchuck','has','jam','who','farmer']
当我尝试按列表排序时,注释行仅按字典键排序。我的做法不正确。结果应该是一个按上述索引长度递增顺序的列表。任何建议。
【问题讨论】:
-
您将如何比较密钥?
-
您不能按键对字典进行排序。根据定义,字典没有排序。
标签: python sorting dictionary