2015-06-05 138 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相应的值因为它保持输入值的顺序。