2015-06-05 134 views
0

我是python的新手。 在Python中,我想根據字母數字鍵對字典項進行排序。基於包含字母數字值的鍵排序python字典

代碼片段如下:

items={'100 kg': u"apple", '500 kg': u"cabbage", '1020 kg': u"banana", '259 GB': u"carrot"} 

我希望用他們按升序數量排序。 有什麼辦法可以在Python中做到這一點?

添加, 我使用建議的技術對字典鍵進行排序。在此之後,我想添加排序的關鍵字及其相應的值在另一個新的詞典中,以便我可以以排序的方式獲得詞典,但是新詞典不按照我插入的順序存儲數據。

因此,我使用Python的orderedDict。

對於這個我使用代碼:

import collections 

items={'100 kg': u"apple", '500 kg': u"cabbage", '1020 kg': u"banana", '259 kg': u"carrot"} 
sorted_keys = sorted(items, key = lambda x : int(x.split()[0])) 
sorted_capacity = collections.OrderedDict() 
for j in sorted_keys: 
    for i in items: 
     if j == i: 
      print i 
      sorted_capacity[j]=items[j] 
      break 

在這裏,我得到錯誤爲:AttributeError的:「模塊」對象有沒有屬性「OrderedDict」 什麼可能是這個原因?

+0

你需要一個字典作爲輸出?這是不可能的,因爲字典是無序的數據類型 – nu11p01n73R

+0

看看OrderedDict(https://docs.python.org/2/library/collections.html#collections.OrderedDict) – DNA

+0

http://stackoverflow.com/問題/ 17888331 /排序字母數字鍵 - 在python的字典 –

回答

1

由於python字典無序,因此無法對字典進行排序。

所有你能得到的是鍵或值的排序列表作爲

>>> items={'100 kg': u"apple", '500 kg': u"cabbage", '1020 kg': u"banana", '259 GB': u"carrot"} 
>>> sorted(items, key = lambda x : int(x.split()[0])) 
['100 kg', '259 GB', '500 kg', '1020 kg'] 
+0

你不能在邏輯上排序公斤與千兆字節 – jamylak

+0

我使用上述技術排序字典鍵。 – beginner

0

我用

sorted(items, key = lambda x : int(x.split()[0]))

排序我的字典裏的鑰匙,以後我已存儲密鑰和orderedDict相應的值因爲它保持輸入值的順序。