【问题标题】:Python Dictionary: Sorting TroublePython 字典:排序问题
【发布时间】:2012-07-11 00:38:10
【问题描述】:

我以为我是通过清除字典来对字典进行排序,然后按照我想要的顺序重新组装它,但由于某种原因,它会按照开始的方式重新排序。

如果有人可以帮助我,这是代码

from operator import itemgetter

n = {}
d = {
 'a': ['2', 'ova', 'no'], 
 'b': ['23', 'movie', 'yes'], 
 'c': ['5', 'show', 'yes'], 
 'd': ['17', 'ova', 'yes'], 
 'e': ['1', 'movie', 'no']
}

for i in d:
    print i, d[i]

print '\n'

l = d.items()
l.sort(key=itemgetter(1)) #l is now sorted by the value of the string holding the integers
d.clear()

for i in l:
    print i[0], i[1]
    d[i[0]] = i[1] 

print '\n'

for i in d:
    print i, d[i] #Why does the dictionary come out to be the same it started from

【问题讨论】:

标签: python list sorting dictionary


【解决方案1】:

字典本质上是无序的(因为它们使用哈希键 - 这是唯一但任意的)[这是一个常见问题解答] - 您可能需要考虑使用保留插入顺序的 OrderedDict(在 2.7+ 中)或PyPi 的配方 - 否则,如果您需要订购,则需要将条目保存在列表或其他序列中。

【讨论】:

    【解决方案2】:

    正如 Jon 所指出的,字典没有顺序。通过放弃订购,您可以获得快速查找。不过,您可能不需要它来保持订单,因为您有自己喜欢的排序顺序:

    d = {'a':['2', 'ova', 'no'], 'b':['23', 'movie', 'yes'], 'c':['5', 'show', 'yes'], 'd':['17', 'ova', 'yes'], 'e':['1', 'movie', 'no']}
    sorted_items = sorted(d.items(), key=itemgetter(1))
    for i,v in sorted_items:
        print i, v
    

    【讨论】:

      猜你喜欢
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多