如何用Python中的键对字典进行排序

任何人都可以告诉我如何排序:

{'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}

{'a': [1, 2, 3], 'b': ['blah', 'bhasdf', 'asdf'], 'c': ['one', 'two'],'d': ['asdf', 'wer', 'asdf', 'zxcv']}

? 谢谢!

更新1,代码示例:

所以我在做语言学。 一篇文章被分解为存储在数据库中的单词,并具有各种属性,包括段ID和句子ID。 任务:试图重建原文。

从数据库中获取500个连续的词

words = Words.objects.all()[wordId:wordId+500]
# I first create paragraphs, through which I can loop later in my django template,
# and in each para will be a list of words (also dictionaries). 
# So i am trying to get a dictionary with values that are lists of dictionaries. 
# 'pp' i make just for shorthanding a long-named variable.
paras={}
para_high = para_low =  words[0].belongs_to_paragraph
for w in words:
    last_word = w
    pp = w.belongs_to_paragraph
    if pp >para_high:
        para_high = pp
    if pp < para_low:
        para_low = pp
    if pp in paras:
        paras[pp].append(w)
    else:
        list = [w]
        paras[pp] = list
# Since there are blank lines between paragraphs, in rebuilding the text as it 
    #  looked originally, I need to insert blank lines. 
    # Since i have the ID's of the paragraphs and they go somewhat like that: 1,3,4,8,9 
    #(the gaps between 1 & 3 and 4 & 8 i have to fill in with something else, 
    # which is why i had para_low and para_high to loop the range. 
isbr = True
for i in range(para_low, para_high+1):
    if i in paras:
        isbr = True
    else:
        if isbr:
            paras[i]=['break']
            isbr = False
        else:
            paras[i]=[]

然而,在这一点上,如果我试图循环使用字典并重新构建文本,稍后的某些段落会出现在先前的段落之前,而这样做并不会。

更新2,循环代码:

        {% for k,v in wording.iteritems()  %}
        {% if v[0] == 'break' %}
        <br/>
        {% else %}
        </div><div class="p">{% for word in v %}{% if word.special==0%} {% endif %}<span class="word {% if word.special == 0%}clickable{% endif%}" wid="{{word.id}}" special="{{word.special}}" somethingElse={{word.somethingElse}}>{{ word.word }}</span>{% endfor %}
        {% endif %}
    {% endfor %}

口述没有订单。

你可以调用排序,但这只是给你一个排序的键列表:

>>> sorted(d)
['a', 'b', 'c', 'd']

你可以把它看作一个迭代器并对键值元组进行排序,但是你刚刚得到了一个元组列表。 这与字典不一样。

>>> sorted(d.items())
[
 ('a', [1, 2, 3]),
 ('b', ['blah', 'bhasdf', 'asdf']),
 ('c', ['one', 'two']),
 ('d', ['asdf', 'wer', 'asdf', 'zxcv'])
]

如果你使用Python 2.7或更新的版本,你也可以考虑使用OrderedDict

字典子类,记录添加的订单条目

例如:

>>> d = collections.OrderedDict(sorted(d.items()))
>>> for k, v in d.items():
>>>     print k, v
a [1, 2, 3]
b ['blah', 'bhasdf', 'asdf']
c ['one', 'two']
d ['asdf', 'wer', 'asdf', 'zxcv']

正确的答案是,如果您需要排序顺序的字典项目,则应在循环字典时使用sorted()函数:

for k, v in sorted(d.items()):
    print k, ':', v

要么

for k in sorted(d):
   print d[k]

或类似。

OrderedDict提到的是有命令的字典。 订单与排序不同。 你可以创建一个排序的OrderedDict,是的,但只要你添加一个新的密钥,它就不再被排序。 因此,无论如何您需要使用sorted()来在每次使用之前或每次操作之后对其进行分类。 OrderedDict因此只比普通字典慢,占用内存更多,而不需要添加任何东西。

OrderedDict不是用于排序字典,而是用于字典中的某些排序不是排序的字典。 例如,如果您想按照添加的顺序显示内容,或者希望用户能够随意排列内容。

更新:进一步的解释

为什么OrderedDict不是解决方案? 因为OrderedDict没有排序。

考虑一个标准的字典:

>>> d = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5}

它没有排序,如下所示,'c'会在'b'之前出现。 它也没有顺序,如果我们添加新的东西,它看起来像随机顺序:

>>> d['g'] = 6
>>> d['i'] = 8
>>> d
{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8}

好的,那么让我们使用OrderedDict:

>>> o = OrderedDict(sorted({'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5}.items()))
>>> o
OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5)])

啊哈! 排序! 所以OrderedDict的作品!? 没有。

>>> o['i'] = 8
>>> o['g'] = 6
>>> o
OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('i', 8), ('g', 6)])

什么? g在我以后结束了!!? 为什么!? 因为OrderedDict没有排序,所以它是有序的。 它记得你添加东西的顺序。 不是排序。 这意味着每次使用它时都需要先进行分类。 一个OrderedDict只会保持排序,只要你不添加键。 但如果你不打算修改它,那么你不需要字典。 你也可以有一个列表。 这是你从排序()中得到的结果:

>>> sorted(o.items())
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('i', 8)]

但是,这与标准字典一样好,所以OrderedDictionary并没有帮助:

>>> sorted(d.items())
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('i', 8)]

结论因此,每次你想以一种排序的方式遍历字典时,你需要这样做:

>>> for k in sorted(o):
...   print k, o[k]
... 
a 0
b 1
c 2
d 3
e 4
f 5
g 6
i 8

这不管你用什么字典。 OrderedDict并没有真正帮助你,因为它不关心排序,只是你添加的顺序。


值得注意的是,Python有许多字典实现,它们按照排序顺序维护键。 考虑使用纯Python和快速C实现的sortedcontainers模块。 与基于对方的其他快速和功能完整的实现进行性能对比。

例如:

>>> from sortedcontainers import SortedDict
>>> d = {'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}
>>> s = SortedDict(**d)
>>> s.keys()
SortedSet(['a', 'b', 'c', 'd'])

由于它支持快速获取/设置操作并按键排序项目迭代,因此您还可以完全替换使用字典的SortedDict。

链接地址: http://www.djcxy.com/p/18117.html

上一篇: How to sort dictionaries by keys in Python

下一篇: python dictionary values sorting