我是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” 什么可能是这个原因?
你需要一个字典作为输出?这是不可能的,因为字典是无序的数据类型 – nu11p01n73R
看看OrderedDict(https://docs.python.org/2/library/collections.html#collections.OrderedDict) – DNA
http://stackoverflow.com/问题/ 17888331 /排序字母数字键 - 在python的字典 –